fork download
  1. #include <stdio.h>
  2.  
  3. int count=0;
  4.  
  5. int cmp(int x, int y) // compare x and y
  6. {
  7. return x > y; // 1 if x > y, 0 otherwise
  8. }
  9.  
  10. void swap(int *x, int *y)
  11. {
  12. int tmp = *x;
  13.  
  14. *x = *y;
  15. *y = tmp;
  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.  
  23. for (size_t i = 0; i < n - 1; ++i) {
  24. int swapcount=0;
  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. swapcount=1;
  29. count++;
  30. }
  31. }
  32. if (swapcount==0)
  33. break;
  34. }
  35.  
  36. for (size_t i = 0; i < n; ++i) {
  37. printf("%d ", a[i]);
  38. }
  39. printf("\n");
  40.  
  41. printf("%d回",count);
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9 
10回