Trying to learn how to implement a Quicksort implementation, I cannot understand why it is not sorting correctly.
Using this sequence:
6, 7, 12, 5, 9, 8, 65, 3
He returns this:
3, 5, 7, 8, 9, 65, 12, 6
It seems that a little, but not all. What did I miss?
Here is my code:
static void Main(string[] args) { QuickSort qs = new QuickSort(); int[] arr = new int[] { 6, 7, 12, 5, 9, 8, 65, 3 }; foreach (int l in arr) { Console.Write(l + ", "); } int left = 0; int right = arr.Count() - 1; int[] arrr = qs.DoQuickSort(ref arr, left, right); Console.WriteLine("Sorted List: "); foreach (int i in arrr) { Console.Write(i + " "); } Console.ReadLine(); } public int Partition(int[] array, int left, int right, int PivotIndex) { int pivValue = array[PivotIndex]; array = Swap(ref array, PivotIndex, right); int storeIndex = left; for (int i = PivotIndex; i < right-1; i++) { if (array[i] <= pivValue) { array = Swap(ref array, i, storeIndex); storeIndex = storeIndex + 1; } } array = Swap(ref array, storeIndex, right); return storeIndex; } public int[] Swap(ref int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; return arr; } public int[] DoQuickSort(ref int[] array, int left, int right) { if (right > left) { int PivIndex = (left + right) / 2; int newPivIndex = Partition(array, left, right, PivIndex); DoQuickSort(ref array, left, newPivIndex - 1); DoQuickSort(ref array, newPivIndex + 1, right); } return array; }
source share