Why is my implementation of Hoare's Partition here not working?

You can run what I've written down from here: http://ideone.com/uLPi8v

Or refer to the snippet I've posted below:

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
int HoarePartition(vector<int> & in){
	int startIndex = 0; 
	int stopIndex = in.size()-1;
	int pivot = in[ startIndex ];

	cout << "=== Before Partition ===" <<endl;
	printVector(in);

	while (true){
		while ( in[ startIndex ] <= pivot ){
			startIndex++;
		}
		while ( in[ stopIndex ] > pivot ){
			stopIndex--;
		}
		if( startIndex < stopIndex ){
			// swap!
			int swapCup = in[ startIndex ];
			in[ startIndex ] = in[ stopIndex ];
			in[ stopIndex ] = swapCup;
		}
		else{
			cout << "=== After Partition ===" << endl;
			printVector(in);
			return stopIndex;
		}
	}
}


I'm picking the partition as the first element, but this is what I seem to get returned back:

1
2
3
4
=== Before Partition ===
5, 9, 8, 4, 1, 2
=== After Partition ===
5, 2, 1, 4, 8, 9


Which is clearly incorrect.

The only difference between what I have and the pseudocode is that startIndex is initialized as "startIndex-1" which would be some invalid entry in the
vector the first time it is run...

What's going wrong and how to I rectify it?
Last edited on
On line 10, replace <= with <
Topic archived. No new replies allowed.