桶排序

来源:互联网 发布:雅奇小土豆编程破解版 编辑:程序博客网 时间:2024/05/21 19:45

排序算法之桶排序

基于非比较的排序

#include<stdio.h>#include<stdlib.h>#include<string.h>//桶排序---基于非比较的排序//以空间换时间//适用元素长度相同的数组排序:如123,254,444,100  (都是三位数)//1 找到最大值、最小值//2 根据最大值、最小值建桶//3 数据元素入桶//4 各桶内排序//5 桶内元素放回原数组//6 释放typedef struct node{int nValue;struct node *pNext;}MyBucket;void BucketSort(int a[],int nlen){int i;int nMax,nMin;int nBase;int nNum;int newlen;int nIndex;MyBucket **pBucket=NULL;MyBucket *ptemp=NULL;MyBucket *pMark=NULL;if(a==NULL || nlen<=0) return ;//遍历获得数组中最大值,最小值nMax=a[0];nMin=a[0];for(i=0;i<nlen;i++){if(a[i]>nMax) nMax=a[i];if(a[i]<nMin) nMin=a[i];}//数据分析---位数,被除数//位数,被除数nNum=nMax;i=0;while (nNum){i++;nNum/=10;}//被除数nBase=1;while(i>1){nBase*=10;i--;}//桶个数newlen=nMax/nBase-nMin/nBase+1;//创建桶pBucket=(MyBucket**)malloc(sizeof(MyBucket*)*newlen);//初始化桶memset(pBucket,0,sizeof(MyBucket*)*newlen);//元素入桶for(i=0;i<nlen;i++){//入桶的下标nIndex=a[i]/nBase-nMin/nBase;//申请节点并初始化ptemp=(MyBucket*)malloc(sizeof(MyBucket));ptemp->nValue=a[i];ptemp->pNext=NULL;//插入排序----头插入法,小的放在前面if(pBucket[nIndex]==NULL ||pBucket[nIndex]->nValue > ptemp->nValue){ptemp->pNext=pBucket[nIndex];pBucket[nIndex]=ptemp;}else{//标记小链表头pMark=pBucket[nIndex];while (pMark->pNext!=NULL &&ptemp->nValue >pMark->pNext->nValue){pMark=pMark->pNext;}ptemp->pNext=pMark->pNext;pMark->pNext=ptemp;}}//把桶中元素放回原数组nIndex=0;for(i=0;i<newlen;i++){pMark=pBucket[i];while (pMark){a[nIndex]=pMark->nValue;pMark=pMark->pNext;nIndex++;}}//释放桶空间//先释放小链表for(i=0;i<newlen;i++){pMark=pBucket[i];while (pMark){ptemp=pMark;pMark=pMark->pNext;free(ptemp);ptemp=NULL;}}//释放桶空间free(pBucket);pBucket=NULL;}int main(){int i;int len;int a[]={123,321,432,566,777,890,990,661,555,554,898,112};len=sizeof(a)/sizeof(a[0]);BucketSort(a,len);for(i=0;i<len;i++){printf("%d ",a[i]);}system("pause");return 0;}


原创粉丝点击