Advertisement
shevitza

SortedListOfStrings

Dec 16th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.10 KB | None | 0 0
  1. //Write a program that sorts an array of strings using the quick sort algorithm
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9.  
  10. class SortString
  11. {
  12. public static int CompareStrings(string s1, string s2)
  13. {
  14.  
  15. //Compare two string lexicographically
  16. char[] first = s1.ToCharArray();
  17. char[] second = s2.ToCharArray();
  18. bool areEqual = false;
  19. int minLength = Math.Min(second.Length, first.Length);
  20. int msg = -1; //1 - s1 is smaller, 2-s2 is smaller, 0 s1 and s2 are equal
  21.  
  22. for (int i = 0; i < minLength; i++)
  23. {
  24. if (first[i] == second[i])
  25. {
  26. msg = 0;
  27. areEqual = true;
  28. continue;
  29. }
  30. if (first[i] > second[i])
  31. {
  32. msg = 2;
  33. areEqual = false;
  34. break;
  35. }
  36. else if (first[i] < second[i])
  37. {
  38. msg = 1;
  39. areEqual = false;
  40. break;
  41. }
  42. }
  43. return msg;
  44.  
  45. }
  46. static List<string> QuickSort(List<string> array)
  47. {
  48. //Ivaylo Kenov changed code for int list
  49. if (array.Count <= 1)
  50. {
  51. return array;
  52. }
  53.  
  54. string pivot = array[array.Count / 2];
  55. List<string> less = new List<string>();
  56. List<string> greater = new List<string>();
  57.  
  58. for (int i = 0; i < array.Count; i++)
  59. {
  60. if (i != (array.Count / 2))
  61. {
  62. if (CompareStrings(array[i], pivot) == 1)
  63. {
  64. less.Add(array[i]);
  65. }
  66. else
  67. {
  68. greater.Add(array[i]);
  69. }
  70. }
  71. }
  72.  
  73. return ConcatenateArrays(QuickSort(less), pivot, QuickSort(greater));
  74. }
  75.  
  76. static List<string> ConcatenateArrays(List<string> less, string pivot, List<string> greater)
  77. {
  78. //Ivaylo Kenov changed code for int list
  79. List<string> result = new List<string>();
  80.  
  81. for (int i = 0; i < less.Count; i++)
  82. {
  83. result.Add(less[i]);
  84. }
  85.  
  86. result.Add(pivot);
  87.  
  88. for (int i = 0; i < greater.Count; i++)
  89. {
  90. result.Add(greater[i]);
  91. }
  92.  
  93. return result;
  94. }
  95. static void Main(string[] args)
  96. {
  97. List<string> arrayOfIntegers = new List<string>() { "Dima", "Anna", "Ella", "Nina", "Vassil", "Pesho" };
  98. List<string> sortedArray = QuickSort(arrayOfIntegers);
  99. for (int i = 0; i < sortedArray.Count; i++)
  100. {
  101. Console.WriteLine(sortedArray[i]);
  102. }
  103.  
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement