Advertisement
Guest User

Untitled

a guest
May 27th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. using System;
  2. using System.Linq.Expressions;
  3.  
  4. namespace CountingSort {
  5. class Program {
  6. static void Main(string[] args) {
  7. int[] arr = new int[] {1, 2, 5, -1, -2, 3};
  8. Console.WriteLine(string.Join(", ", CountingSort(arr)));
  9. }
  10.  
  11. public static int[] CountingSort(int[] array) {
  12. int[] counting = new int[GetMax(array) - GetMin(array) + 1];
  13. for (int i = 0; i < array.Length; i++) {
  14. counting[array[i] - GetMin(array)] += 1;
  15. }
  16.  
  17. int[] numbersIndexes = new int[counting.Length];
  18. for (int i = 1; i < counting.Length; i++) {
  19. numbersIndexes[i] = numbersIndexes[i - 1] + counting[i - 1];
  20. }
  21.  
  22. int[] sortedArray = new int[array.Length];
  23. for (int i = 0; i < array.Length; i++) {
  24. sortedArray[numbersIndexes[array[i] - GetMin(array)]++] = array[i];
  25. }
  26.  
  27. return sortedArray;
  28. }
  29.  
  30.  
  31. public static int GetMin(int[] array) {
  32. int min = array.Length == 0 ? 0 : array[0];
  33. for (int i = 0; i < array.Length; i++) {
  34. if (array[i] < min) {
  35. min = array[i];
  36. }
  37. }
  38.  
  39. return min;
  40. }
  41.  
  42. public static int GetMax(int[] array) {
  43. int max = array.Length == 0 ? 0 : array[0];
  44. for (int i = 0; i < array.Length; i++) {
  45. if (array[i] > max) {
  46. max = array[i];
  47. }
  48. }
  49.  
  50. return max;
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement