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. 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.  
  21. for (size_t i = 0; i < n - 1; ++i) {
  22. int count = 0; // 周の最初に0へ戻す
  23. for (size_t j = 0; j < n - 1 - i; ++j) {
  24. if (cmp(a[j], a[j+1])) {
  25. swap( &a[j] , &a[j+1] );
  26. count++; // 入れ替えたら+1
  27. }
  28. }
  29. if (count == 0) { // 入れ替え0回なら整列完了
  30. break;
  31. }
  32. }
  33.  
  34. for (size_t i = 0; i < n; ++i) {
  35. printf("%d ", a[i]);
  36. }
  37. printf("\n");
  38.  
  39. return 0;
  40. }
  41.  
  42. /*
  43. ①21行目の下にint count =0;
  44. ②if (cmp( ? , ? )) {swap( ? , ? );}の{}中にcount++;
  45. ③26行目の下にif (count == 0){break;}
  46. なお、今回においてはcountで数える必要がないため、++count;の行はcount =1;;に置き換え、ON/OFF判定にすることも可能である。
  47. */
Success #stdin #stdout 0s 5348KB
stdin
Standard input is empty
stdout
1 1 2 3 4 5 5 6 9