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. int *select(int p[], size_t len)
  17. {
  18.  
  19.  
  20.  
  21. int *pos = p; // pointer to the highest-precedence element
  22.  
  23. for (size_t i = 0; i < len; ++i) {
  24. if (cmp(p[i], *pos)) {
  25. pos = &p[i];
  26. }
  27. }
  28.  
  29. return pos;
  30. }
  31.  
  32.  
  33.  
  34.  
  35. void disp(int p[], size_t len)
  36. {
  37. for (size_t i = 0; i < len; ++i) {
  38. printf("%d ", p[i]);
  39. }
  40. printf("\n");
  41. }
  42.  
  43. int main(void)
  44. {
  45. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}; // array to be sorted
  46. size_t n = sizeof a / sizeof a[0]; // number of elements
  47.  
  48. for (size_t i = 0; i < n - 1; ++i) {
  49.  
  50. int *q = select( a+i , n-1 );
  51. if (cmp( *q, a[i] )) {
  52. swap( q, &a[i] );
  53. }
  54.  
  55. }
  56.  
  57. disp(a, n);
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
1 1 2 3 4 0 0 5 6