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