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}; // array to be sorted
  19. size_t n = sizeof a / sizeof a[0]; // number of elements
  20. size_t count = 0;
  21. for (size_t i = 0; i < n - 1; ++i) {
  22. for (size_t j = 0; j < n - 1 - i; ++j) {
  23. if(cmp(a[j],a[j+1])){
  24. swap(&a[j],&a[j+1]);
  25. count++;
  26. }
  27. }
  28. }
  29. for (size_t i = 0; i < n; ++i) {
  30. printf("%d ", a[i]);
  31. printf("swap count: %zu\n", count);
  32. }
  33. printf("\n");
  34. // your code goes here
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 5344KB
stdin
Standard input is empty
stdout
1 swap count: 10
1 swap count: 10
2 swap count: 10
3 swap count: 10
4 swap count: 10
5 swap count: 10
5 swap count: 10
6 swap count: 10
9 swap count: 10