QuickSort problem

hello, i am a c++ noob, here is my work on quick sort problem,
i don't know why it doesn't work, any one can point out the mistake will be very thankful.
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<iostream>
using namespace std;

void Swap(int,int);
void QuickSort (int [], int, int)

int main()
{
	int array[] = {693, 600, 766, 60, 203, 700, 567, 568, 216, 331};
	cout <<"the original sequence is:" <<endl;
	for (int i=0; i<10; i++)
	{
		cout <<array[i] <<" ";
	}
	cout <<endl;

	QuickSort (array, 0, 9);

	cout <<"the sorted sequence is:" <<endl;
	for (int i=0; i<10; i++)
	{
		cout <<array[i] <<" ";
	}
	cout <<endl;

	return 0;
}

void Swap(int x,int y)
{
	int temp = x;
	x = y;
	y = temp;
}

void QuickSort (int array[], int x, int y)
{
	int pivotPlace, checkPt, start;
	checkPt = y;
	pivotPlace = x;
	start = y+1;

	if (x == y)
		return;

	while (checkPt != pivotPlace)
	{
		for (int i=start-1; i>=pivotPlace; i--)
		{
			checkPt = i;
			if (array[i] < array[pivotPlace])
			{
				Swap (array[i], array[pivotPlace]);
				start = pivotPlace;
				checkPt =-1;
				pivotPlace = i;
				break;
			}
		}

		if (checkPt == pivotPlace)
			checkPt = pivotPlace;

		else
		{
			for(int j=start+1; j<=pivotPlace; j++)
			{
				checkPt = j;
				if (array[j] > array[pivotPlace])
				{
					Swap (array[j], array[pivotPlace]);
					start = pivotPlace;
					checkPt = -1;
					pivotPlace = j;		
					break;
				}
			}
		}
	}
	QuickSort (array, x, pivotPlace-1);
	QuickSort (array, pivotPlace+1, y);
}
Last edited on
Your Swap function should look like this:
1
2
3
4
5
6
void Swap(int& x,int& y)
{
	int temp = x;
	x = y;
	y = temp;
}


Notice the ampersand (&) signs? They tell the compiler that any changes made to x and y should be applied to the original variables that you passed to the function. This is called passing by reference.

Here an explanation in detail: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/ and here a general explanation about references: http://www.learncpp.com/cpp-tutorial/611-references/
Last edited on
@ fransje: or just use std::swap
http://www.cplusplus.com/reference/algorithm/swap/
still doesn't work

it seems some wrong in the QuickSort block
however i cant figure it out
attach the debugger and see where you are going wrong.
swap code should be like this
1
2
3
4
5
6
void Swap(int* x,int* y)
{
	int temp =* x;
	*x = *y;
	*y = temp;
}



and call it like this

Swap (&array[i], array[&pivotPlace]);
thanks all

i revised the swap function and the line 43
1
2
	if (x == y)
		return;


to be like this
1
2
if (x >= y)
		return;


than it works
Topic archived. No new replies allowed.