Reputation: 57
I've problem with my implementation of quick sort. Problem looks randomly and the sorted array is never sorted.
I based on this pseudocode:
1 procedure quick sort1(l, r);
2 begin
3 if ` < r then
4 t ← A[l]; {t — pivot}
5 s ← l;
6 for i ← l + 1 to r do {move elements around pivot}
7 if A[i] < t then
8 s ← s + 1;
9 swap(A[s], A[i]);
10 end if;
11 end for;
12 swap(A[l], A[s]);
13 quick sort1(l, s − 1); {recursive call for both subarrays}
14 quick sort1(s + 1, r);
15 end if;
16 end.
There is my code:
public void QuickSort(int[] A, int l, int r)
{
int t;
int s = 0;
if (l < r)
{
t = A[l];
s = l;
for (int i = l + 1; i < r; i++)
{
if (A[i] < t)
{
s = s + 1;
swaponator(ref A[s], ref A[i]);
}
}
swaponator(ref A[l], ref A[s]);
QuickSort(A, l, s - 1);
QuickSort(A, s + 1, r);
}
}
but it does not work - i have no idea why, i debug this and still nothing.
please, can someone give me a tip?
Best regards.
Upvotes: 1
Views: 186
Reputation: 67
Their might be problem if duplicate entries are there, so
if (A[i] <= t);
and r should be passed as 'n-1' initially.
Upvotes: 0
Reputation: 73
The problem is in the for loop. To iterate all the numbers in the array, the variable i must reach the value of r.
for (int i = l + 1; i <= r; i++)
Upvotes: 1