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