Tuesday, November 9, 2010

Radix sort algorithm implementation in c using counting sort

/* radix sort */

#include 
#include 
#include  

#define LEN  72 /* maximum string length */
#define K  256 /* number of possible characters */
//#define MAX_STRINGS 50



void counting_sort (unsigned char *A[], 
unsigned char *B[], int n, int h) {
 int  C[K];
 int  i, j;

 for (i=0; i
 /* all counts are now zero */

 for (j=0; j

 /* C[i] is number of times character i occurs */

 for (i=1; i
 /* C[i] is number of times i or less occurs */

 for (j=n-1; j>=0; j--) {

  /* place elements in the array from largest to smallest */
  /* -1 is because arrays start out at 0 in C */

  B[C[A[j][h]]-1] = A[j];
  C[A[j][h]]--;
 }
}

/* this radix sort sorts the n pointers to strings 
of size d in the array A
 * by the strings they point to.
 */
void radix_sort (unsigned char *A[], int n, int d) {
 int  i, j;
 unsigned char *B[50];

 /* we're assuming here that digit 0 is the highest order digit,
  * like in real life, not like in the book
  */
 for (i=d-1; i>=0; i--) {

  /* stable sort A into B */

  counting_sort (A, B, n, i);

  /* copy the results back into A */

  for (j=0; j }
}


/* main program */

int main () {
 unsigned char A[50][5+1],
   *Ap[50],s[50];
 int  i, n;

        clrscr() ; 

 /* get a bunch of strings into the array A */

 for (n=0;n<8;n++) {
  gets (s);
  if (feof (stdin)) break;

  /* make sure the string is no longer than LEN */

  s[LEN] = 0;

  /* make sure the string is no shorter than LEN */

  while (strlen(s)

  /* put the string into the next position in A */

  strcpy (A[n++],s);
 }

 /* make Ap an array of pointers to the strings in A */

 for (i=0; i
 /* sort the pointers */

 radix_sort (Ap,n,LEN);

 /* print them out */

 for (i=0; i

 getch() ; 

 return 0 ;
}

No comments:

Post a Comment