Why chose selection sort?
When the number of data is very small, selection sort is more efficient than quicksort ,its plan is to set a length k,if array is smaller than k,use selection_quick,or use quicksort.
What's the selection sort?
Repeatly scan the array to select the smallest element,then put it behind array sorted.
Procesure
<span style="font-size:10px;">#include<stdlib.h>
#define THRESHOLD 5
int less(char x,char y)
{
if(x<=y)
return 1;
else
return 0;
}
void exchange(char a[],int i,int j)
{
char temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
int partition(char a[],int lo,int hi)
{
int i=lo,j=hi+1;
while(1)
{
while(less(a[++i],a[lo]))
{
if(i==hi) break;
}
while(less(a[lo],a[--j]))
{
if(j==lo)break;
}
if(i>=j)break;
exchange(a,i,j);
}
exchange(a,lo,j);
return j;
}
void selection_sort(char a[],int length)
{
int i,j;
int min;
for(i=0;i<length;i++)
{
min=i;
for(j=i+1;j<length;j++)
{
if(less(a[j],a[min]))
min=j;
}
exchange(a,i,min);
}
}
void sort(char a[],int lo,int hi)
{
int j;
int length=hi-lo+1;
if(lo>=hi)return ;
if(length<=THRESHOLD){
selection_sort(a,length);
return;
}
j=partition(a,lo,hi);
sort(a,0,j-1);
sort(a,j+1,hi);
}
int main()
{
int i;
char a[]={'J','A','A'};
int len=3;
sort(a,0,len-1);
for(i=0;i<len;i++)
printf("%c ",a[i]);
return 0;
}</span>
Output: A J J