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