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