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.  
  11. int tmp = *x;
  12.  
  13. *x = *y;
  14. *y = tmp;
  15.  
  16. }
  17.  
  18. int main(void)
  19. {
  20. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}; // array to be sorted
  21. size_t n = sizeof a /sizeof a[0]; // number of elements
  22. int swap_count=0;
  23. int count2=0;
  24.  
  25. for (size_t i = 0; i < n - 1; ++i) {
  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. swap_count ++;
  30. count2++;
  31. }
  32. }
  33. if (count2==0)
  34. break;
  35. count2=0;
  36. }
  37.  
  38.  
  39.  
  40. for (size_t i = 0; i < n; ++i) {
  41. printf("%d ", a[i]);
  42. }
  43. printf("\n");
  44. printf("%d",swap_count);
  45. return 0;
  46. }
Success #stdin #stdout 0s 5352KB
stdin
Standard input is empty
stdout
9 6 5 5 4 3 2 1 1 
24