fork download
  1. #include <stdio.h>
  2.  
  3. int cmp(int x, int y) { return x > y; }
  4.  
  5. void swap(int *x, int *y)
  6. {
  7. int tmp = *x;
  8. *x = *y;
  9. *y = tmp;
  10. }
  11.  
  12. int main(void)
  13. {
  14. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5};
  15. size_t n = sizeof a / sizeof a[0];
  16. size_t count = 0; // swap回数
  17. size_t passes = 0; // 外側ループを回った周回数
  18.  
  19. for (size_t i = 0; i < n - 1; ++i) {
  20. int swapped = 0; // 周の最初に0
  21. ++passes; // 周回数を+1
  22. for (size_t j = 0; j < n - 1 - i; ++j) {
  23. if (cmp(a[j], a[j + 1])) {
  24. swap(&a[j], &a[j + 1]);
  25. ++count;
  26. swapped = 1; // 入れ替えたら1
  27. }
  28. }
  29. if (!swapped) break; // 1回も入れ替わらなければ終了
  30. }
  31.  
  32. for (size_t i = 0; i < n; ++i) {
  33. printf("%d ", a[i]);
  34. }
  35. printf("\n");
  36. printf("swap count = %zu\n", count);
  37. printf("passes = %zu\n", passes);
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5336KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
swap count = 10
passes     = 5