Algorithm Implementation/Sorting/Pigeonhole sort

All the examples currently on this page seem to be implementations of counting sort and not pigeonhole sort. Pigeonhole sort, when sorting a complex data structure with a key, keeps track of all the elements on a certain key (because equal elements are still distinct); rather than just keep a count like counting sort (which is only applicable to simple value types).

Contents

voidpigeonhole_sort(int*low,int*high,intmin,intmax){/* used to keep track of the size of the list we're sorting */intcount;/* pointer into the list we're sorting */int*current;/* size of range of values in the list (ie, number of pigeonholes we need)*/constintsize=max-min+1;/* our array of pigeonholes */intholes[size];/* make absolutely certain that the pigeonholes start out empty */for(inti=0;i<size;++i)holes[i]=0;/* Populate the pigeonholes. */for(current=low;current<=high;current++)holes[*current-min]+=1;/* Put the elements back into the array in order. */for(current=low,count=0;count<size;count++)while(holes[count]-->0)*current++=count+min;}

Note that min and max could also easily be determined within the function.

publicstaticvoidpigeonhole_sort(int[]a){// size of range of values in the list (ie, number of pigeonholes we need)intmin=a[0],max=a[0];for(intx:a){min=Math.min(x,min);max=Math.max(x,max);}finalintsize=max-min+1;// our array of pigeonholesint[]holes=newint[size];// Populate the pigeonholes.for(intx:a)holes[x-min]++;// Put the elements back into the array in order.inti=0;for(intcount=0;count<size;count++)while(holes[count]-->0)a[i++]=count+min;}

defpigeonhole_sort(a):# size of range of values in the list (ie, number of pigeonholes we need)my_min=min(a)my_max=max(a)size=my_max-my_min+1# our list of pigeonholesholes=[0]*size# Populate the pigeonholes.forxina:asserttype(x)isint,"integers only please"holes[x-my_min]+=1# Put the elements back into the array in order.i=0forcountinxrange(size):whileholes[count]>0:holes[count]-=1a[i]=count+my_mini+=1