Skip to content

Commit 65e33f7

Browse files
authoredOct 24, 2020
Merge pull request #1149 from vidz-1/patch-4
Create C#
2 parents 702277d + c4aa9e6 commit 65e33f7

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
 

‎Sorting/Radix Sort/C#/radix_sort.cs

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// C# implementation of Radix Sort
2+
using System;
3+
4+
class GFG
5+
{
6+
public static 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+
public static void countSort(int[] arr, int n, int exp)
18+
{
19+
int[] output = new int[n]; // output array
20+
int i;
21+
int[] count = new int[10];
22+
23+
//initializing all elements of count to 0
24+
for(i = 0; i < 10; i++)
25+
count[i] = 0;
26+
27+
// Store count of occurrences in count[]
28+
for (i = 0; i < n; i++)
29+
count[ (arr[i]/exp)%10 ]++;
30+
31+
// Change count[i] so that count[i] now contains actual
32+
// position of this digit in output[]
33+
for (i = 1; i < 10; i++)
34+
count[i] += count[i - 1];
35+
36+
// Build the output array
37+
for (i = n - 1; i >= 0; i--)
38+
{
39+
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
40+
count[ (arr[i]/exp)%10 ]--;
41+
}
42+
43+
// Copy the output array to arr[], so that arr[] now
44+
// contains sorted numbers according to current digit
45+
for (i = 0; i < n; i++)
46+
arr[i] = output[i];
47+
}
48+
49+
// The main function to that sorts arr[] of size n using
50+
// Radix Sort
51+
public static void radixsort(int[] arr, int n)
52+
{
53+
// Find the maximum number to know number of digits
54+
int m = getMax(arr, n);
55+
56+
// Do counting sort for every digit. Note that instead
57+
// of passing digit number, exp is passed. exp is 10^i
58+
// where i is current digit number
59+
for (int exp = 1; m/exp > 0; exp *= 10)
60+
countSort(arr, n, exp);
61+
}
62+
63+
// A utility function to print an array
64+
public static void print(int[] arr, int n)
65+
{
66+
for (int i = 0; i < n; i++)
67+
Console.Write(arr[i] + " ");
68+
}
69+
70+
// Driver program to test above functions
71+
public static void Main()
72+
{
73+
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
74+
int n = arr.Length;
75+
radixsort(arr, n);
76+
print(arr, n);
77+
}
78+
79+
//This code is contributed by vidz-1
80+
}

0 commit comments

Comments
 (0)
Please sign in to comment.