Currently I am learning quick sort. I've followed the quick sort rules; but I have found a strange thing.
The process is just like this picture.
Please help me find where I am fault:

Here is the code:
static void QuickSortFromMiddle(int[] arr, int low, int high)
{
if (low < high)
{
int middleValue = arr[(low+high)/2];
int h = high+1;
int l = low-1;
while (l < h)
{
while (arr[--h] > middleValue && l<h);
while (arr[++l] < middleValue && l<h) ;
if (l >= h)
break;
int temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
}
QuickSortFromMiddle(arr,low,l-1);
QuickSortFromMiddle(arr, h+1, high);
}
}
/// <summary>
///
/// </summary>
static void QuickSort(int[] arr)
{
QuickSortFromMiddle(arr, 0, arr.Length - 1);
}
/// <summary>
///
/// </summary>
static void TestQuickSort()
{
var arr = new[] { 1, 5, 3, 4, 57, 5, 5, 53 };
QuickSort(arr);
foreach (int i in arr)
{
Console.WriteLine(i);
}
}
Here is result (I am so confused....)

as Dukeling said "The pivot is typically moved to either end"
Firstly, I should put the pivot at the end of the array
Secondly,I should put the pivot in the right position of arr(greater than left,and less than right)
here is right process:

The overall algorithm is as follows:
There are several schemes for partitioning, any of which would work, as long as the condition is satisfied. Your partitioning scheme is something i've never seen before. In particular, I've never seen a quick sort partitioning scheme that takes the centrally located value as the pivot. Please see the wikipedia page for some standard partitioning schemes (Eg Lomuto).
Overall, your partition scheme makes the following limitations:
arr[l] and arr[h], you don't even check whether they need to be swapped. You just assume that after the initial moving of l and h (the two inner while loops), all other numbers need to be swapped.You need to make your partition scheme more generic, maybe try understanding and using one of the standard ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With