Advertisement
KnSharp

Untitled

Dec 20th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. int findLargestNum(int * array, int size){
  2.  
  3.   int i;
  4.   int largestNum = -1;
  5.  
  6.   for(i = 0; i < size; i++){
  7.     if(array[i] > largestNum)
  8.       largestNum = array[i];
  9.   }
  10.  
  11.   return largestNum;
  12. }
  13.  
  14. // Radix Sort
  15. void radixSort(int * array, int size){
  16.  
  17.   printf("\n\nRunning Radix Sort on Unsorted List!\n\n");
  18.  
  19.   // Base 10 is used
  20.   int i;
  21.   int semiSorted[size];
  22.   int significantDigit = 1;
  23.   int largestNum = findLargestNum(array, size);
  24.  
  25.   // Loop until we reach the largest significant digit
  26.   while (largestNum / significantDigit > 0){
  27.    
  28.     printf("\tSorting: %d's place ", significantDigit);
  29.     printArray(array, size);
  30.    
  31.     int bucket[10] = { 0 };
  32.    
  33.     // Counts the number of "keys" or digits that will go into each bucket
  34.     for (i = 0; i < size; i++)
  35.       bucket[(array[i] / significantDigit) % 10]++;
  36.    
  37.     /**
  38.      * Add the count of the previous buckets,
  39.      * Acquires the indexes after the end of each bucket location in the array
  40.          * Works similar to the count sort algorithm
  41.      **/
  42.     for (i = 1; i < 10; i++)
  43.       bucket[i] += bucket[i - 1];
  44.    
  45.     // Use the bucket to fill a "semiSorted" array
  46.     for (i = size - 1; i >= 0; i--)
  47.       semiSorted[--bucket[(array[i] / significantDigit) % 10]] = array[i];
  48.    
  49.    
  50.     for (i = 0; i < size; i++)
  51.       array[i] = semiSorted[i];
  52.    
  53.     // Move to next significant digit
  54.     significantDigit *= 10;
  55.    
  56.     printf("\n\tBucket: ");
  57.     printArray(bucket, 10);
  58.   }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement