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