forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* Implemented Trie C# * Added check mark under Trie c# * Fixed syntax * Implemented Counting Sort [C#] * Added counting sort to readme * Update README.md * Code refactoring based on PR feedback * Fixed Travis indent size error
- Loading branch information
1 parent
63ac50b
commit 4cec987
Showing
2 changed files
with
44 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
using System; | ||
|
||
public class CountingSort | ||
{ | ||
|
||
/** | ||
* Sorts the array using counting sort | ||
* Time Complexity: O(n + k) where n is the number of elements in the array and k is the range of input | ||
* Space Complexity: O(n + k) | ||
*/ | ||
public static int[] DoCountingSort(int[] arr) | ||
{ | ||
// finding the maximum value in the array | ||
int maxValue = Int32.MinValue; | ||
foreach (int num in arr) | ||
maxValue = Math.Max(maxValue, num); | ||
|
||
// counting the frequency of each element in the array | ||
int[] frequency = new int[maxValue + 1]; | ||
foreach (int num in arr) | ||
frequency[num]++; | ||
|
||
// modifying each element in the frequency array to the total of all the elements before it | ||
for (int i = 1; i < frequency.Length; i++) | ||
frequency[i] += frequency[i - 1]; | ||
|
||
// constructing the sorted array based on the freqency of each element in ascending order | ||
int[] sortedArr = new int[arr.Length]; | ||
for (int i = 0; i < arr.Length; i++) { | ||
sortedArr[frequency[arr[i]] - 1] = arr[i]; | ||
frequency[arr[i]]--; | ||
} | ||
return sortedArr; | ||
} | ||
|
||
public static void Main() | ||
{ | ||
int[] arr = new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; | ||
int[] sortedArr = DoCountingSort(arr); | ||
foreach (int num in sortedArr) | ||
Console.WriteLine(num); | ||
} | ||
} |