I've been trying to implement quick sort in a particular way and I couldn't find it all over the internet-
The problem is that I have a mistake in my algorithm and I can't figure it out. Can anyone tell me what am I doing wrong?
Here is my code:
public static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int partition(int[] a, int start, int end)
{
int pivot = a[end];
int i = start;
int j = end - 1;
while (i < j)
{
while (i < j && a[i] <= pivot)
i++;
while (i < j && a[j] > pivot)
j--;
swap(a, i, j);
}
swap(a, i+1, end);
return i+1 ;
}
public static void QuickSort(int[] a, int start, int end)
{
if (start >= end)
return;
int p = partition(a, start, end);
QuickSort(a, start, p - 1);
QuickSort(a, p + 1, end);
}
static void Main(string[] args)
{
int[] a = { 9, 1, 4, 7, 3 };
QuickSort(a, 0, a.Length-1);
//PrintArr(a);
}
you partition method has issue.
you should have it like this.
public static int partition(int[] a, int start, int end)
{
int pivot = a[end];
int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{
if (a[j] < pivot)
{
i++;
swap(a, i, j);
}
}
swap(a, i + 1, end);
return (i + 1);
}