c言語でクイックソート
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
#include <stdio.h> #include <stdlib.h> #include <time.h> void dispArrayLine(int a[], int length, int dispTotal){ int total = 0; for(int i=0; i<length; i++){ total += a[i]; printf("%d", a[i]); if(i!=length-1){ printf(" "); }else{ if(dispTotal){ printf(" : %d", total); } printf("\n"); } } } void dispArrayList(int a[], int length){ for(int i=0; i<length; i++){ printf("[%d] : %d\n", i, a[i]); } } void resetArray(int a[], int length){ for(int i=0; i<length; i++){ a[i] = 0; } } void init(){ srand((unsigned)time(NULL)); } double getRandomDouble(){ return (double)rand() / RAND_MAX; } int getRandomInt(int min, int max){ double d = getRandomDouble(); int randomOffset = d * (max - min + 1); return min + randomOffset; } void setRandomIntForArray(int a[], int length, int min, int max){ for(int i=0; i<length; i++){ a[i] = getRandomInt(min, max); } } int getPivot(int a, int b, int c){ if(a > b){ if(b > c){ return b; }else{ return a > c ? c : a ; } }else{ if(a > c){ return a; }else{ return b > c ? c : b ; } } } int getMax(int a, int b, int c){ if(a > b){ return a > c ? a : c ; }else{ return b > c ? b : c ; } } int getMin(int a, int b, int c){ if(a < b){ return a < c ? a : c ; }else{ return b < c ? b : c ; } } void swap(int a[], int l, int r){ int t = a[l]; a[l] = a[r]; a[r] = t; } void quicksort_core(int a[], int length, int left, int right){ if(right <= left){ return; } int l = left; int r = right; int p = getPivot(a[l], a[l+1], a[r]); while(1){ while(a[l]<p){ l++; } while(p<a[r]){ r--; } if(r<=l){ break; } swap(a, l, r); l++; r--; } quicksort_core(a, length, left, l-1); quicksort_core(a, length, r+1, right); } void quicksort(int a[], int length){ int left = 0; int right = length-1; quicksort_core(a, length, left, right); } int main(void){ init(); int length = 30; int a[length]; int min = -9; int max = 9; setRandomIntForArray(a, length, min, max); dispArrayLine(a, length, 1); quicksort(a, length); dispArrayLine(a, length, 1); return 0; } |