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