/*Radix sort using counting sort*/
#include <stdio.h>
#include <conio.h>
#define max 10
void print(int arr[max],int len)
{
int i;
for(i=0;i<len;i++)
printf("%d\t",arr[i]);
printf("\n");
}
void counting_sort_modified(int source_array[max],int destination_array_order[max],int upper_bound,int src_array_length)
{
int temp_buffer[max],i;
for(i=0;i<=upper_bound;i++)
{
temp_buffer[i]=0;
}
for(i=0;i<src_array_length;i++)
{
temp_buffer[source_array[i]]=temp_buffer[source_array[i]]+1;
}
for(i=1;i<=upper_bound;i++)
{
temp_buffer[i]=temp_buffer[i]+temp_buffer[i-1];
}
for(i=src_array_length-1;i>=0;i--)
{
destination_array_order[temp_buffer[source_array[i]]-1]=i;//source_array[i]; Returns the array of positions of sorted elements.
temp_buffer[source_array[i]]=temp_buffer[source_array[i]]-1;
}
}
void array_copy(int src[max],int dest[max],int length)
{
int iterator=0;
while(iterator < length)
{
dest[iterator]=src[iterator];
iterator++;
}
}
void radix_sort(int source_array[max],int src_array_length)
{
int destination_array[max],stuffed_array[max],iterator,divisor=0,flag;
do
{
flag=iterator=0;
while(iterator < src_array_length)
{
stuffed_array[iterator]=(int)(source_array[iterator]/pow(10,divisor))%10;
if(stuffed_array[iterator])
{
flag=1;
}
iterator++;
}
if(flag)
{
counting_sort_modified(stuffed_array,destination_array,9,src_array_length);
iterator=0;
while(iterator < src_array_length)
{
stuffed_array[iterator]=source_array[destination_array[iterator]];
iterator++;
}
array_copy(stuffed_array,source_array,src_array_length);
}
divisor++;
}while(flag);
}
int main()
{
int arr[]={183,265,149,43,123,627};
print(arr,6);
radix_sort(arr,6);
print(arr,6);
getche();
return 1;
}
0 comments:
Post a Comment