Bucket sequencing implementation (no optimizations)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.