Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. nclude<iostream>
  2. using namespace std;
  3.  
  4. // A function to do counting sort of arr[] according to
  5. // the digit represented by exp.
  6. int countSort(int arr[], int n, int exp)
  7. {
  8.  
  9.     int output[n]; // output array
  10.     int i, count[n] ;
  11.     for (int i=0; i < n; i++)
  12.        count[i] = 0;
  13.  
  14.     // Store count of occurrences in count[]
  15.     for (i = 0; i < n; i++)
  16.         count[ (arr[i]/exp)%n ]++;
  17.  
  18.     // Change count[i] so that count[i] now contains actual
  19.     // position of this digit in output[]
  20.     for (i = 1; i < n; i++)
  21.         count[i] += count[i - 1];
  22.  
  23.     // Build the output array
  24.     for (i = n - 1; i >= 0; i--)
  25.     {
  26.         output[count[ (arr[i]/exp)%n] - 1] = arr[i];
  27.         count[(arr[i]/exp)%n]--;
  28.     }
  29.  
  30.     // Copy the output array to arr[], so that arr[] now
  31.     // contains sorted numbers according to curent digit
  32.     for (i = 0; i < n; i++)
  33.         arr[i] = output[i];
  34. }
  35.  
  36.  
  37. // The main function to that sorts arr[] of size n using Radix Sort
  38. void sort(int arr[], int n)
  39. {
  40.     // Do counting sort for first digit in base n. Note that
  41.     // instead of passing digit number, exp (n^0 = 0) is passed.
  42.     countSort(arr, n, 1);
  43.  
  44.     // Do counting sort for second digit in base n. Note that
  45.     // instead of passing digit number, exp (n^1 = n) is passed.
  46.     countSort(arr, n, n);
  47. }
  48.  
  49. // A utility function to print an array
  50. void printArr(int arr[], int n)
  51. {
  52.     for (int i = 0; i < n; i++)
  53.         cout << arr[i] << " ";
  54. }
  55.  
  56. // Driver program to test above functions
  57. int main()
  58. {
  59.     // Since array size is 7, elements should be from 0 to 48
  60.     int arr[] = {40, 12, 45, 32, 33, 1, 22};
  61.     int n = sizeof(arr)/sizeof(arr[0]);
  62.     cout << "Given array is n";
  63.     printArr(arr, n);
  64.  
  65.     sort(arr, n);
  66.  
  67.     cout << "nSorted array is n";
  68.     printArr(arr, n);
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement