fork download
  1. #include <stdio.h>
  2. int swapcount =0;
  3. int cmp(int x, int y) // compare x and y
  4. {
  5. return x > y; // 1 if x > y, 0 otherwise
  6. }
  7. void swap(int *x, int *y)
  8. {
  9. swapcount++;
  10. int tmp = *x;
  11.  
  12. *x = *y;
  13. *y = tmp;
  14.  
  15. }
  16.  
  17. int main(void)
  18. {
  19. int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}; // array to be sorted
  20. size_t n = sizeof a / sizeof a[0]; // number of elements
  21.  
  22. for (size_t i = 0; i < n - 1; ++i) {
  23. int count=0;
  24. for (size_t j = 0; j < n - 1 - i; ++j) {
  25. if (cmp( a[j] , a[j+1])) {
  26. swap( &a[j] , &a[j+1] );
  27. count=1;
  28. }
  29. }
  30. if(count==0){
  31. break;
  32. }
  33. }
  34. for(size_t i=0;i<n;++i){
  35. printf("%d",a[i]);
  36. }
  37. printf("\n");
  38. printf("swap関数の呼び出し回数%d",swapcount);
  39. return 0;
  40. }
Success #stdin #stdout 0s 5348KB
stdin
Standard input is empty
stdout
112345569
swap関数の呼び出し回数10