Skip to content

Instantly share code, notes, and snippets.

@schauhan232
Created July 9, 2021 14:10
Show Gist options
  • Save schauhan232/aadd2237f536e5aa6465ca902640cf61 to your computer and use it in GitHub Desktop.
Save schauhan232/aadd2237f536e5aa6465ca902640cf61 to your computer and use it in GitHub Desktop.
Hackerrank: Counting Sort 2 C#
//Learned theory from https://www.youtube.com/watch?v=HkvChUv9dDg
class Program
{
public static void Main(string[] args)
{
var array = new int[] { 19, 10, 12, 10, 24, 25, 22 };
//generate empty array to add values on index
// keeping +1 in max to avoid index out error can be handle by other condition though
var arrayForOutPut = Enumerable.Repeat(0, array.Max() + 1).ToList();
// final array
var finalArray = new List<int>();
for (int i = 0; i <= array.Count() - 1; i++)
{
arrayForOutPut[array[i]] = arrayForOutPut[array[i]] + 1;
}
for (int i = 0; i <= arrayForOutPut.Count() - 1; i++)
{
if (arrayForOutPut[i] == 0)
continue;
while (arrayForOutPut[i] != 0)
{
finalArray.Add(i);
arrayForOutPut[i] = arrayForOutPut[i] - 1;
}
}
Console.WriteLine($"Input array : {string.Join(",", array)}");
Console.WriteLine($"Output array : {string.Join(",", finalArray)}");
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment