|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace Algorithms.NET.Sorting.CountingSort |
| 7 | +{ |
| 8 | + public class CountingSortAlgorithm |
| 9 | + { |
| 10 | + /// <summary> |
| 11 | + /// Sorting an array of positive integers in ascending order using CountingSort algorithm, Time complexity of O(n). |
| 12 | + /// </summary> |
| 13 | + /// <param name="list">Array of numbers to sort</param> |
| 14 | + /// <returns>Sorted Array in ascending order.</returns> |
| 15 | + public static int[] SortAscending(int[] list) |
| 16 | + { |
| 17 | + return Sort(list, false); |
| 18 | + } |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Sorting an array of positive integers in Descending order using CountingSort algorithm, Time complexity of O(n). |
| 22 | + /// </summary> |
| 23 | + /// <param name="list">Array of numbers to sort</param> |
| 24 | + /// <returns>Sorted Array in Descending order.</returns> |
| 25 | + public static int[] SortDescending(int[] list) |
| 26 | + { |
| 27 | + return Sort(list, true); |
| 28 | + } |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Sorting an array of positive integers using CountingSort algorithm, Time complexity of O(n). |
| 32 | + /// </summary> |
| 33 | + /// <param name="list">Array of numbers to sort</param> |
| 34 | + /// <param name="sortDescending">Boolean value specifying whether sorting should be done in descending order</param> |
| 35 | + /// <returns>A sorted Array</returns> |
| 36 | + private static int[] Sort(int[] list, bool sortDescending) |
| 37 | + { |
| 38 | + int[] sortedList = new int[list.Length]; |
| 39 | + list.CopyTo(sortedList, 0); |
| 40 | + |
| 41 | + int max = sortedList[0]; |
| 42 | + for (int i = 1; i < sortedList.Length; i++) |
| 43 | + if (sortedList[i] > max) |
| 44 | + max = sortedList[i]; |
| 45 | + |
| 46 | + int[] countingArray = new int[max + 1]; |
| 47 | + |
| 48 | + for (int i = 0; i < sortedList.Length; i++) |
| 49 | + { |
| 50 | + countingArray[sortedList[i]]++; |
| 51 | + } |
| 52 | + |
| 53 | + if (!sortDescending) |
| 54 | + { |
| 55 | + int k = 0; |
| 56 | + for (int i = 0; i < countingArray.Length; i++) |
| 57 | + for (int j = 0; j < countingArray[i]; j++) |
| 58 | + sortedList[k++] = i; |
| 59 | + } |
| 60 | + else |
| 61 | + { |
| 62 | + int k = 0; |
| 63 | + for (int i = countingArray.Length - 1; i >= 0; i--) |
| 64 | + for (int j = 0; j < countingArray[i]; j++) |
| 65 | + sortedList[k++] = i; |
| 66 | + } |
| 67 | + |
| 68 | + |
| 69 | + return sortedList; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments