Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cab190a

Browse files
authored
Merge pull request fnplus#628 from Raman1309/patch-5
RadixSort.cpp
2 parents 63b8d0c + 8fbf09f commit cab190a

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
// A utility function to get maximum value in arr[]
5+
int getMax(int arr[], int n)
6+
{
7+
int mx = arr[0];
8+
for (int i = 1; i < n; i++)
9+
if (arr[i] > mx)
10+
mx = arr[i];
11+
return mx;
12+
}
13+
14+
// A function to do counting sort of arr[] according to
15+
// the digit represented by exp.
16+
void countSort(int arr[], int n, int exp)
17+
{
18+
int output[n]; // output array
19+
int i, count[10] = {0};
20+
21+
// Store count of occurrences in count[]
22+
for (i = 0; i < n; i++)
23+
count[ (arr[i]/exp)%10 ]++;
24+
25+
// Change count[i] so that count[i] now contains actual
26+
// position of this digit in output[]
27+
for (i = 1; i < 10; i++)
28+
count[i] += count[i - 1];
29+
30+
// Build the output array
31+
for (i = n - 1; i >= 0; i--)
32+
{
33+
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
34+
count[ (arr[i]/exp)%10 ]--;
35+
}
36+
37+
// Copy the output array to arr[], so that arr[] now
38+
// contains sorted numbers according to current digit
39+
for (i = 0; i < n; i++)
40+
arr[i] = output[i];
41+
}
42+
43+
// The main function to that sorts arr[] of size n using
44+
// Radix Sort
45+
void radixsort(int arr[], int n)
46+
{
47+
// Find the maximum number to know number of digits
48+
int m = getMax(arr, n);
49+
50+
// Do counting sort for every digit. Note that instead
51+
// of passing digit number, exp is passed. exp is 10^i
52+
// where i is current digit number
53+
for (int exp = 1; m/exp > 0; exp *= 10)
54+
countSort(arr, n, exp);
55+
}
56+
57+
58+
void print(int arr[], int n)
59+
{
60+
for (int i = 0; i < n; i++)
61+
cout << arr[i] << " ";
62+
}
63+
64+
// Driver program to test above functions
65+
int main()
66+
{
67+
int n;
68+
cout<<"\n Size : ";
69+
cin>>n;
70+
71+
int arr[n];
72+
cout<<"\n Enter values in array : ";
73+
for(int i=0;i<n;i++)
74+
cin>>arr[i];
75+
76+
radixsort(arr, n);
77+
print(arr, n);
78+
return 0;
79+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /