fork(1) 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. int count=0;
  21. int forcount=0;
  22. int fornaicount=0;
  23.  
  24. for (size_t i = 0; i < n - 1; ++i) {
  25. fornaicount=0;
  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. count++;
  30. fornaicount++;
  31.  
  32. }
  33. forcount++;
  34. }
  35. if(fornaicount==0){
  36. break;
  37. }
  38. }
  39.  
  40. printf("swapの回数%d\n",count);
  41. printf("21行目の繰り返し回数%d\n",forcount);
  42.  
  43. for (size_t i = 0; i < n; ++i) {
  44. printf("%d ", a[i]);
  45. }
  46. printf("\n");
  47.  
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
swapの回数24
21行目の繰り返し回数35
9 6 5 5 4 3 2 1 1