fork download
  1. #include <stdio.h>
  2. static int count;
  3.  
  4. int cmp(int x, int y) // compare x with y
  5. {
  6. return x < y; // 1 if x < y, 0 otherwise
  7. }
  8.  
  9. void swap(int *x, int *y)
  10. {
  11. int tmp = *x;
  12. *x = *y;
  13. *y = tmp;
  14. count++;
  15.  
  16. }
  17.  
  18. size_t select(int p[], size_t len)
  19. {
  20. size_t pos = 0; // position of the highest-precedence element
  21. for (size_t i = 0; i < len; ++i) {
  22. if (!cmp(p[pos], p[i])) {
  23. pos = i;
  24. }
  25. }
  26. return pos;
  27. }
  28.  
  29. void disp(int p[], size_t len)
  30. {
  31. for (size_t i = 0; i < len; ++i) {
  32. printf("%d ", p[i]);
  33. }
  34. printf("\n");
  35. }
  36.  
  37. int main(void)
  38. {
  39. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5};
  40. size_t n = sizeof a / sizeof a[0];
  41.  
  42. for (size_t i = 0; i < n - 1; ++i) {
  43. size_t j = i + 1 + select(a + i + 1, n - i - 1);
  44. if (cmp(a[j], a[i])) {
  45. swap(&a[j], &a[i]);
  46. }
  47. }
  48.  
  49. disp(a, n);
  50. printf("%d", count);
  51. return 0;
  52. }
Success #stdin #stdout 0s 548KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
4