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