Recursion issues with quicksort

Hi guys, I have a problem I'm trying to solve for a long time. I am supposed to write a quicksort function to sort numbers of integer type from 0 to 1000. This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
void quicksort(int k[], int left, int right)
{
//	left is lowest index of array k
//	right is highest index of array k

	int pivot=k[left], i=left, j=right, swap;
	do
	{
		do  
		{
			i++;
		}
		while (k[i]<pivot);
		do
		{
			if (i>j)
				break;
			j--;
		}
		while (k[j]>pivot);

		if (i<j)
		{
			swap=k[i];
			k[i]=k[j];
			k[j]=swap;
		}
		else
		{
			swap=k[left];
			k[left]=k[j];
			k[j]=swap;
		}
		cout << endl << endl;

//		testing
//		for (int a=0; a<=right; a++)
//			{
//				cout << k[a] << '\t';
//			}		
	}
	while (i<j);

//	recursion
	if (left<right)
	{
		quicksort(k, left, j--);
		quicksort(k, j++, right);
	}
}


I realised by checking the sequence with for-loop that my partitions seems to be working, but not my recursion. I managed to find a sample code that works by using pivot=k[(left+right)/2], but my assignment states that pivot needs to be = k[left].

So, I was wondering how the recursion can be changed so that the function would work.

Thank you!
I think you meant j-1 and j+1 on lines 47 and 48.

Your partitioning needs improvement; you're using too many loops. It can be done in a single loop.
Also, use std::swap().
Last edited on
Thank you for your help! I didn't know that increments and decrements cannot be used in function parameters. Now my recursion seems to be working but there are still some odd errors (the sort gets progressively inaccurate somehow). So does the problem lie with the loops that I am using instead?
Topic archived. No new replies allowed.