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.  
  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. size_t count = 0;
  21. size_t passes = 0;
  22.  
  23. for (size_t i = 0; i < n - 1; ++i) {
  24. int swapped = 0;
  25. ++passes;
  26. for (size_t j = 0; j < n - 1 - i; ++j) {
  27. if (cmp(a[j], a[j + 1])) {
  28. swap(&a[j], &a[j + 1]);
  29. ++count;
  30. swapped = 1;
  31. }
  32. }
  33. if (!swapped) break;
  34. }
  35.  
  36. for (size_t i = 0; i < n; ++i) {
  37. printf("%d ", a[i]);
  38. }
  39. printf("\n");
  40. printf("swap count = %zu\n", count);
  41. printf("passes = %zu\n", passes);
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 5356KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
swap count = 10
passes     = 5