You are on page 1of 2

#include<stdio.

h>
#include<stdlib.h>
int getMax(int arr[], int n){ // A function to get maximum value in array arr[];

int max = arr[0]; //don't forget to initialise the value of max, either
this way or initialize it with a number lower than the minimum of the given array
for (int i = 1; i < n; i++){
if (arr[i] > max){
max = arr[i];
}
}
return max;
}

void countSort(int arr[], int n, int exp){ // A function to do counting sort of


arr[] according to
// the digit
represented by exp.
int output[n]; // output array
int i, count[10] = {0};

for (i = 0; i < n; i++){ // Store count of


occurrences in count[]
count[ (arr[i]/exp)%10 ]++;
}

for (i = 1; i < 10; i++){ // Change count[i] so that


count[i] now contains actual position of this digit in output[]
count[i] += count[i - 1];
}

for (i = n - 1; i >= 0; i--){ // Build the output array


output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; //read
carefully how the index is manipulated relating arr[], ccount, output.
count[ (arr[i]/exp)%10 ]--;
}

for (i = 0; i < n; i++){ // Copy the output array


to arr[], so that arr[] now contains sorted numbers according to current digit
arr[i] = output[i];
}
}

void RadixSort(int arr[], int n){ // The function that sorts


arr[] of size n using Radix Sort
int m = getMax(arr, n); // Find the maximum number
to know number of digits
// number,
exp is passed. exp is 10^i where i is current digit number
for (int exp = 1; m/exp > 0; exp *= 10){
countSort(arr, n, exp);
}
}

// function to print our final sorted array


void print(int arr[], int n){
for (int i = 0; i < n; i++){
cout<<arr[i]);
}
cout<<"\n";
}

int main(){
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]); // sizeof(arr)=8*4 Bytes (
(size of the array) * (size of each element) )

//sizeof(arr[0])=4 Bytes (size of an int variable).


RadixSort(arr, n);
print(arr, n);
return 0;
}

You might also like