Often, when a list is sorted, the elements being sorted are just keys to other values. For example, if you are sorting files by their size, the sizes need to stay connected to their respective files. You cannot just take the size numbers and output them in order, you need to output all the required file information.
The counting sort is used if you just need to sort a list of integers. Rather than using a comparison, you create an integer array whose index range covers the entire range of values in your array to sort. Each time a value occurs in the original array, you increment the counter at that index. At the end, run through your counting array, printing the value of each non-zero valued index that number of times.
For example, consider an array . All of the values are in the range , so create an array of zeroes, . The results of each iteration follow:
i arr[i] result
0 1 [0, 1, 0, 0]
1 1 [0, 2, 0, 0]
2 3 [0, 2, 0, 1]
3 2 [0, 2, 1, 1]
4 1 [0, 3, 1, 1]
Now we can print the sorted array: .
Challenge
Given an unsorted list of integers, use the counting sort method to sort the list and then print the sorted list.
Given an unsorted list of integers, use the counting sort method to sort the list and then print the sorted list.
Question from hackerrank.
Solution in C# -
class Solution {
static int[] countingSort(int[] arr) {
int[] index = new int[100];
for(int i=0; i<arr.Length; i++)
index[arr[i]]++;
List<int> array = new List<int>();
for(int i=0; i<index.Length; i++)
{
for(int j=1; j<=index[i]; j++)
array.Add(i);
}
return array.ToArray();
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
int[] result = countingSort(arr);
textWriter.WriteLine(string.Join(" ", result));
textWriter.Flush();
textWriter.Close();
}
}
Post a Comment