Attempting to learn from doing an implementation of Quicksort, I cannot find out why it's not sorting properly.
Using this sequence:
6, 7, 12, 5, 9, 8, 65, 3
It returns this:
3, 5, 7, 8, 9, 65, 12, 6
It seems to sort somewhat, but not all. What have I missed?
Here's 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;
}