diff --git a/c-cpp/13_sorts/sort.c b/c-cpp/13_sorts/sort.c old mode 100644 new mode 100755 index 41e13cc..50cb463 --- a/c-cpp/13_sorts/sort.c +++ b/c-cpp/13_sorts/sort.c @@ -158,11 +158,111 @@ void radix_sort_test() return; } +struct barrel { + int node[10]; + int count;/* the num of node */ +}; +int partition(int a[],int left,int right) +{ + int i = left; + int j = right; + int key = a[left]; + + while(i < j) + { + while((i < j)&& (a[j] >= key)) + { + j--; + } + if (i < j) + { + a[i] = a[j]; + } + while((i < j) && a[i] <= key) + { + i++; + } + + if (i= right) + { + return; + } + + q = partition(a,left,right); + quick_sort(a,left,(q - 1)); + quick_sort(a,(q + 1),right); + return; +} + +void bucket_sort(int data[], int size) +{ + int max, min, num, pos; + int i, j, k; + struct barrel *pBarrel; + + max = min = data[0]; + for (i = 1; i < size; i++) { + if (data[i] > max) { + max = data[i]; + } else if (data[i] < min) { + min = data[i]; + } + } + num = (max - min + 1) / 10 + 1; + pBarrel = (struct barrel*)malloc(sizeof(struct barrel) * num); + memset(pBarrel, 0, sizeof(struct barrel) * num); + + /* put data[i] into barrel which it belong to */ + for (i = 0; i < size; i++) { + k = (data[i] - min + 1) / 10;/* calculate the index of data[i] in barrel */ + (pBarrel + k)->node[(pBarrel + k)->count] = data[i]; + (pBarrel + k)->count++; + } + + pos = 0; + for (i = 0; i < num; i++) { + if ((pBarrel + i)->count != 0) + { + quick_sort((pBarrel+i)->node, 0, ((pBarrel+i)->count)-1);/* sort node in every barrel */ + + for (j = 0; j < (pBarrel+i)->count; j++) { + data[pos++] = (pBarrel+i)->node[j]; + } + } + } + free(pBarrel); +} + +void bucket_sort_test() +{ + int a[] = {78, 17, 39, 26, 72, 94, 21, 12, 23, 91}; + int size = sizeof(a) / sizeof(int); + printf("\r\n bucket sort test ..."); + bucket_sort(a, size); + dump(a,size); + +} int main() { count_sort_test(); radix_sort_test(); + + bucket_sort_test(); return 0; }