Objective:
To solve problem of sorting the array contains duplicate keys .
Plan:
Let v be partitioning item a[lo].
a. if a[i]<v:exchange a[lt] with a[i]; increment both lt and i.
b. if a[i]>v:exchange a[gt] with a[i];decrement gt.
c. if a[i]=v,increment i.
Element :
lt ,increment from lo
i ,increment from lo
gt, decrement from hi
Procesure:
//sort for duplicate keys
#include<stdio.h>
#define MAX 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;
}
void sort(char a[],int lo,int hi)
{
int i,lt,gt;
char v;
if(hi<=lo)return ;
lt=lo;
gt=hi;
v=a[lo];
i=lo;
while(i<=gt)
{
if(a[i]<v)
{
exchange(a,i,lt);
++i;
++lt;
}
else if(a[i]>v)
{
exchange(a,i,gt);
--gt;
}
else
++i;
}
sort(a,lo,lt-1);
sort(a,gt+1,hi);
}
int main()
{
int i;
char a[MAX];
for(i=0;i<MAX;i++)
scanf("%c",&a[i]);
sort(a,0,MAX-1);
for(i=0;i<MAX;i++)
printf("%c ",a[i]);
return 0;
}
Input: bakaa
Output:a a a b k