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 a14124b

Browse files
Merge pull request #2 from ghulamghousdev/ghulamghousdev-patch-1-4
Create RadixSort.cpp
2 parents c48a559 + 1521590 commit a14124b

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

‎Sorting Algorithms/RadixSort.cpp‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// C++ implementation of Radix Sort
2+
#include <iostream>
3+
using namespace std;
4+
5+
// A utility function to get maximum value in arr[]
6+
int getMax(int arr[], int n)
7+
{
8+
int mx = arr[0];
9+
for (int i = 1; i < n; i++)
10+
if (arr[i] > mx)
11+
mx = arr[i];
12+
return mx;
13+
}
14+
15+
// A function to do counting sort of arr[] according to
16+
// the digit represented by exp.
17+
void countSort(int arr[], int n, int exp)
18+
{
19+
int output[n]; // output array
20+
int i, count[10] = { 0 };
21+
22+
// Store count of occurrences in count[]
23+
for (i = 0; i < n; i++)
24+
count[(arr[i] / exp) % 10]++;
25+
26+
// Change count[i] so that count[i] now contains actual
27+
// position of this digit in output[]
28+
for (i = 1; i < 10; i++)
29+
count[i] += count[i - 1];
30+
31+
// Build the output array
32+
for (i = n - 1; i >= 0; i--) {
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+
// A utility function to print an array
58+
void print(int arr[], int n)
59+
{
60+
for (int i = 0; i < n; i++)
61+
cout << arr[i] << " ";
62+
}
63+
64+
// Driver Code
65+
int main()
66+
{
67+
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
68+
int n = sizeof(arr) / sizeof(arr[0]);
69+
70+
// Function Call
71+
radixsort(arr, n);
72+
print(arr, n);
73+
return 0;
74+
}

0 commit comments

Comments
(0)

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