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