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.  
  18. for (size_t i = 0; i < n - 1; ++i) {
  19. for (size_t j = 0; j < n - 1 - i; ++j) {
  20. if (cmp(a[j], a[j + 1])) {
  21. swap(&a[j], &a[j + 1]);
  22. ++count; // swapするたびに+1
  23. }
  24. }
  25. }
  26.  
  27. for (size_t i = 0; i < n; ++i) {
  28. printf("%d ", a[i]);
  29. }
  30. printf("\n");
  31. printf("swap count = %zu\n", count); //回数を表示
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
swap count = 10