forked from Rishabh062/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Radix - sort
70 lines (57 loc) · 1.32 KB
/
Radix - sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
using namespace std;
// A utility function to get maximum value in arr[]
int getMax(int arr[], int size)
{
int max = arr[0];
for (int i = 1; i < size; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
void CountingSort(int arr[], int size, int div)
{
int output[size];
int count[10] = {0};
for (int i = 0; i < size; i++)
count[ (arr[i]/div)%10 ]++;
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
for (int i = size - 1; i >= 0; i--)
{
output[count[ (arr[i]/div)%10 ] - 1] = arr[i];
count[ (arr[i]/div)%10 ]--;
}
for (int i = 0; i < size; i++)
arr[i] = output[i];
}
void RadixSort(int arr[], int size)
{
int m = getMax(arr, size);
for (int div = 1; m/div > 0; div *= 10)
CountingSort(arr, size, div);
}
int main()
{
int size;
cout<<"Enter the size of the array: "<<endl;
cin>>size;
int arr[size];
cout<<"Enter "<<size<<" integers in any order"<<endl;
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
cout<<endl<<"Before Sorting: "<<endl;
for(int i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
RadixSort(arr, size);
cout<<endl<<"After Sorting: "<<endl;
for(int i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}