Advertisement
NickG

radix sort

May 10th, 2012
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. void radixsort(int array[], int size) {
  2.  
  3. //Set max equal to the greatest element of the array
  4. int max = 0;
  5. for (int i = 0; i < size; i++) {
  6.    if (array[i] > max)
  7.       max = array[i];
  8.    }
  9.  
  10. for(int pow10=1; max != 0; max/=10, pow10*=10) {
  11.    int buffer[size], bucket[10] = {0};
  12.  
  13.  
  14.       //Calculate the bucket numbers
  15.       for (int i = 0; i < size; i++)
  16.          bucket[(array[i] / pow10) % 10]++;
  17.      
  18.       //Sum the bucket numbers
  19.       for (int i = 1; i<10; i++)
  20.          bucket[i] += bucket[i - 1];
  21.  
  22.       //Bucket sort the array into a buffer
  23.       for  (int i = size - 1; i >= 0; i--)
  24.          buffer[--bucket[(array[i] / pow10) % 10]] = array[i];
  25.  
  26.       //Move the sorted elements back into array
  27.       for (int i = 0; i < size; i++)
  28.          array[i] = buffer[i];
  29.   }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement