fork download
  1.  
  2. #include <stdio.h>
  3.  
  4. int swap_count = 0;
  5.  
  6. int cmp(int x, int y)
  7. {
  8. return x > y;
  9. }
  10.  
  11. void swap(int *x, int *y)
  12. {
  13. swap_count++;
  14.  
  15. int tmp = *x;
  16. *x = *y;
  17. *y = tmp;
  18. }
  19.  
  20. int main(void)
  21. {
  22. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5};
  23. size_t n = sizeof a / sizeof a[0];
  24.  
  25. for (size_t i = 0; i < n - 1; ++i) {
  26. int count = 0;
  27.  
  28. for (size_t j = 0; j < n - 1 - i; ++j) {
  29. if (cmp(a[j], a[j + 1])) {
  30. swap(&a[j], &a[j + 1]);
  31. count++;
  32. }
  33. }
  34.  
  35. if (count == 0) {
  36. break;
  37. }
  38. }
  39.  
  40. for (size_t i = 0; i < n; ++i) {
  41. printf("%d ", a[i]);
  42. }
  43.  
  44. printf("\n");
  45. printf("swapの回数:%d回\n", swap_count);
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 5356KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
swapの回数:10回