Bucket sorting algorithm is mainly used in the case of uniform data distribution, where the input data is assumed to be all the keywords distributed between 0~100, so we are divided into 10 with [0..9], storage sort, b[i][] in the x/10==i element, and then *b[i] to insert sort, Copy to end of array A.
Insert the sort code (preceding to give):
int InsertSort(int *a,int n){ //对长度为n的数组,进行插入排序,下标0~n-1 int i,j,key; for(j=1;j<n;j++){ key=a[j]; i=j-1; while(i>=0&&a[i]>key){//从右到左比较,当前元素大于关键值,当前元素后移 a[i+1]=a[i]; i--; } //i==-1(所有元素后移)||a[i]<=key,key插入到i+1位置 a[i+1]=key; } return0;}
Bucket sort:
voidBucketsort (int*a,intN) {int*c=New int[Ten];memsetC0,sizeof(int)*Ten);int**b=New int*[ One]; for(intI=0; i<=Ten; i++) {b[i]=New int[n+1]; }//Assign the elements in the a array to each corresponding bucket and record the number of elements of the bucket for(intI=1; i<=n;i++) {b[a[i]/Ten][c[a[i]/Ten]++]=a[i]; }//each bucket to be inserted in a sort for(intI=1; i<=n;i++) {if(c[i]>0) Insertsort (B[i],c[i]); }//Copy to original array intk=1; for(intI=1; i<=n;i++) {if(C[i]) for(intj=0; j<c[i];j++) {a[k++]=b[i][j]; } }//Reclaim space DeleteC for(intI=0; i<=Ten; i++) {DeleteB[i]; }DeleteB;}
Test code:
int main () {int a [9 ]={0 , 35 , 32 , 12 , 43 , 56 , 77 , 45 , 55 } PT (a , 8 ) Bucketsort (a , 8 ) PT (a , 8 ) return 0 }
Test results:
Bucket sequencing implementation (no optimizations)