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