fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void main();
  5.  
  6. /*アルゴリズム*/
  7. void QuickSotr(int *data, int n);
  8.  
  9. /*便利系*/
  10. int MyRandom(int maxInt);
  11. void ArrayPrint(int *array, int n);
  12. void ArrayShuffle(int *array, int n);
  13. void ArrayCreate(int *array, int n);
  14. void Swap(int *array, int *data2);
  15.  
  16. void main() {
  17. printf("クイックソート?\n");
  18.  
  19. int n = 20;
  20. int A[20];;
  21.  
  22.  
  23. printf("クイックソートもどきテスト\n");
  24. ArrayCreate(A,n);
  25. ArrayShuffle(A, n);
  26. ArrayPrint(A, n);
  27.  
  28. QuickSotr(A, n);
  29.  
  30. printf("ソート完了\n");
  31. ArrayPrint(A, n);
  32.  
  33. }
  34.  
  35. /**
  36. * クイックソートもどき
  37. **/
  38. void QuickSotr(int *array , int n) {
  39.  
  40. int i;
  41. int right = 0;
  42. int pivot = n - 1; //ケツをPivot化
  43. int location = 0; //中心点
  44.  
  45. if (n <= 0) {
  46. return;
  47. }
  48.  
  49. for (i = 0; i < n - 1; i++) {
  50. if (array[i] < array[pivot]) {
  51. if (location != i)
  52. Swap(&array[location], &array[i]);
  53. location = location + 1;
  54. }
  55. }
  56.  
  57. Swap(&array[pivot],&array[location]);
  58.  
  59. QuickSotr(array, location);//左翼
  60. QuickSotr(&array[location + 1], n - location - 1 );//右翼
  61. }
  62. /**
  63. * クイックソートもどき
  64. **/
  65.  
  66.  
  67. /**
  68. * 便利なメソッド
  69. **/
  70.  
  71. /* myRandomとswapメソッドを使って配列をランダムに混ぜる。*/
  72. void ArrayShuffle(int *array, int n) {
  73. int i;
  74. for (i = 0; i < n; i = i + 1) {
  75. int work = MyRandom(n);
  76. Swap(&array[i], &array[work]);
  77. }
  78. }
  79.  
  80. /* 時間を用いた乱数生成マクロ、 [ maxInt ] に10を入れたら 0-9の乱数を生成する。*/
  81. int MyRandom(int maxInt) {
  82. srand(time(NULL));
  83. return rand() % maxInt;
  84. }
  85.  
  86. void Swap(int *data1, int *data2) {
  87. int work;
  88. work = *data1;
  89. *data1 = *data2;
  90. *data2 = work;
  91. }
  92.  
  93. void ArrayPrint(int *array, int n) {
  94. int i;
  95. printf("{ ");
  96. for (i = 0; i < n; i = i + 1)
  97. if (i != n - 1)
  98. printf("%d , ", array[i]);
  99. else
  100. printf("%d ", array[i]);
  101. printf(" }");
  102. printf("\n");
  103. return;
  104. }
  105. void ArrayCreate(int *array, int n) {
  106. int i;
  107. for (i = 0; i < n; i = i + 1) {
  108. array[i] = i;
  109. }
  110. }
  111.  
  112.  
Runtime error #stdin #stdout 0s 4572KB
stdin
Standard input is empty
stdout
クイックソート?
クイックソートもどきテスト
{ 3 , 0 , 1 , 19 , 2 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18  }
ソート完了
{ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19  }