Advertisement
Guest User

Untitled

a guest
Dec 7th, 2013
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace TestMyQuick
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. int[] numbers = new int[10000];
  14. int len = 10000;
  15.  
  16. Random random = new Random();
  17.  
  18. for (int i = 0; i < len; i++)
  19. {
  20. numbers[i] = random.Next(1000000);
  21. }
  22.  
  23. IterativeQuickSort(numbers);
  24. }
  25.  
  26. public static void IterativeQuickSort(IList<int> collection)
  27. {
  28. Stack<int> stack = new Stack<int>();
  29.  
  30. stack.Push(0);
  31. stack.Push(collection.Count-1);
  32.  
  33. while (stack.Count!=0)
  34. {
  35. int right = stack.Pop();
  36. int left = stack.Pop();
  37.  
  38. if (right - left < 1)
  39. {
  40. continue;
  41. }
  42.  
  43. int pivotNext = Partition(collection, left, right);
  44.  
  45. stack.Push(pivotNext + 1);
  46. stack.Push(right);
  47.  
  48. stack.Push(left);
  49. stack.Push(pivotNext);
  50. }
  51. }
  52.  
  53. static int Partition(IList<int> collection, int left, int right)
  54. {
  55. int index = Median(left, right, collection);
  56. int temp = collection[left];
  57. int pivot = collection[index];
  58. collection[index] = temp;
  59. collection[left] = pivot;
  60.  
  61. int i = left + 1;
  62.  
  63. for (int j = left + 1; j <= right; j++)
  64. {
  65. if (collection[j] < pivot)
  66. {
  67.  
  68. temp = collection[i];
  69. collection[i] = collection[j];
  70. collection[j] = temp;
  71. i++;
  72. }
  73. }
  74.  
  75. temp = collection[left];
  76. collection[left] = collection[i - 1];
  77. collection[i - 1] = temp;
  78. return i - 1;
  79. }
  80.  
  81. static int Median(int left, int right, IList<int> collection)
  82. {
  83. // comparasions += (right - left);
  84. int middle = (right + left) / 2;
  85.  
  86. if ((collection[middle] < collection[left] && collection[middle] > collection[right]) ||
  87. (collection[middle] > collection[left] && collection[middle] < collection[right]))
  88. {
  89. return middle;
  90. }
  91. else if ((collection[right] < collection[middle] && collection[right] > collection[left]) ||
  92. (collection[right] > collection[middle] && collection[right] < collection[left]))
  93. {
  94. return right;
  95. }
  96. else
  97. {
  98. return left;
  99. }
  100. }
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement