Pivot function for a quicksort algorithm.

I'm trying to create a quicksort algorithm.
My pivot function,that returns the pivot's place,looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int pivot(int myArray[],int left,int right){
	
    int pivot=myArray[0];

	while(left!=right){
		while(pivot<myArray[right])
			right--;
		swap(myArray[left],myArray[right]);
		left++;
		while(pivot>myArray[left])
			left++;
		swap(myArray[left],myArray[right]);
		right--;
	}
			
	return right;
     }


Can seomeone please tell me whit this doesnt work?
closed account (o3hC5Di1)
Hi there,

I believe your problem is in not using curly braces for your while-loops, in this statement:

1
2
while(pivot<myArray[right])
			right--;


You decrement right until it's equal to pivot, which at that point is set to myArray[0]. Also, it will probably decrement it until it is equal to left, considering that left is the beginning of the array. So that's where your while(left!=right) will break and return right.

For some very good advice on pivot choice algorithms, please see: http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/quicksort/#pivot-choice

All the best,
NwN
Topic archived. No new replies allowed.