您的位置:首页 > 其它

an improved counting sort for handling negative integers, also take an easy performance compare

2012-06-29 09:02 423 查看
#include<stdio.h>

[code]#include<stdlib.h>
#defineMAX_LENGTH9999

voidprint_array(constinta[],intsize)

{

inti=0;

for(i=0;i<size;i++)

{

printf("%d,",a[i]);

}

printf("\n");

}


/*

assumea[i]>0

*/

voidcounting_sort(constinta[],intb[],intsize,intmaxvalue)

{

inti=0;

for(i=0;i<size;i++)

{

b[i]=0;

}


inttemp[maxvalue+1];

for(i=0;i<=maxvalue;i++)

{

temp[i]=0;

}


for(i=0;i<size;i++)

{

temp[a[i]]+=1;

}


for(i=1;i<=maxvalue;i++)

{

temp[i]=temp[i]+temp[i-1];

}


for(i=size-1;i>=0;i--)

{

b[temp[a[i]]-1]=a[i];

temp[a[i]]=temp[a[i]]-1;

}

}


/*

handlea[i]<0

*/

voidcounting_sort2(constinta[],intb[],intsize,intmaxvalue)

{

inti=0;

intcopyofa[size];

intmin=0;

for(i=0;i<size;i++)

{

b[i]=0;

if(min>a[i])

{

min=a[i];

}

}


intnewmaxvalue=maxvalue-min;

for(i=0;i<size;i++)

{

copyofa[i]=a[i]-min;

}


inttemp[newmaxvalue+1];

for(i=0;i<=newmaxvalue;i++)

{

temp[i]=0;

}


for(i=0;i<size;i++)

{

temp[copyofa[i]]+=1;

}


for(i=1;i<=newmaxvalue;i++)

{

temp[i]=temp[i]+temp[i-1];

}


for(i=size-1;i>=0;i--)

{

b[temp[copyofa[i]]-1]=copyofa[i];

temp[copyofa[i]]=temp[copyofa[i]]-1;

}


for(i=0;i<size;i++)

{

b[i]=b[i]+min;

}

}


voidbubble_sort(constinta[],intb[],intsize)

{

inti=0;

intj=0;

inttemp;


for(i=0;i<size;i++)

{

b[i]=a[i];

}


for(i=0;i<size;i++)

{

for(j=i;j<size;j++)

{

if(b[j]<b[i])

{

temp=b[i];

b[i]=b[j];

b[j]=temp;

}

}

}

}

[/code]

thesecondcountingmethodisimprovedforhandingnegativeintegers.

thefirstisO(n+k),thesecondistwice:O(2n+2k).

writeatestprogramtocomparethesethreesubroutines,


inta[MAX_LENGTH];

[code]intb[MAX_LENGTH];

inti=0;

for(i=0;i<MAX_LENGTH;i++)

{

a[i]=rand();

b[i]=0;

}

for(i=0;i<1000;i++)

{

bubble_sort(a,b,MAX_LENGTH);

counting_sort2(a,b,MAX_LENGTH,RAND_MAX);

counting_sort(a,b,MAX_LENGTH,RAND_MAX);

}

[/code]

theresultasfollow:





wecanseeit’sveryobviousthataO(n2)algorithmisheavyslowerthanO(n+k).tosort9999randomintegersitwillcost195.5mseachtimesortingusebubblebutonly0.17msbyusingcountingmethod(0.35forthesecondcoutningsort,becauseitsrunningtimeisO(2n+2k))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: