I'm a newbie and interested in learning different data structures and algorithms. While implementing quicksort, I found this code works pretty well for partitioning.
int partition(int ar[], int lft, int rgt) {
int left = lft;
int right = rgt;
/*median of three is the best pivot value to accomplish in nlogn time*/
int pivotVal = ar[(left+right)/2];
printf("pivot: %d\n", pivotVal);
/*
-this while loop holds the left and right portion of the
-splitted array together to accomplish partitioning.
*/
while (left < right) {
/*loop for left half array*/
while (ar[left] < pivotVal) { left += 1; };
/*loop for right half array*/
while (ar[right] > pivotVal) { right -= 1; };
/*
-if the above conditions are not met the sub arrays are unsorted
-we need to sort or exchange the values.
*/
if (left < right) {
int cache = ar[left];
ar[left] = ar[right];
ar[right] = cache;
}
}
int pivotIndex = left; /*updated left or right is the pivot index*/
return pivotIndex;
}
Notice the code will get stuck in an infinite loop if there are any duplicate values in the given input array. So I hacked the problem just adding an additional line just after the swapping portion that looks like this:
int partition(int ar[], int lft, int rgt) {
int left = lft;
int right = rgt;
/*median of three is the best pivot value to accomplish in nlogn time*/
int pivotVal = ar[(left+right)/2];
printf("pivot: %d\n", pivotVal);
/*
-this while loop holds the left and right portion of the
-splitted array together to accomplish partitioning.
*/
while (left < right) {
/*loop for left half array*/
while (ar[left] < pivotVal) { left += 1; };
/*loop for right half array*/
while (ar[right] > pivotVal) { right -= 1; };
/*
-if the above conditions are not met the sub arrays are unsorted
-we need to sort or exchange the values.
*/
if (left < right) {
int cache = ar[left];
ar[left] = ar[right];
ar[right] = cache;
}
/*if there are any duplicate value
the above conditions would not met
and the algo will go into an infinite loop.
this if condition checks if there are any
duplicate value if exixts... increase
left or decrease right one to break the loop
*/
if (ar[left] == ar[right]) {
right--; /*if we increase left then pivot index will be the right one*/
}
}
int pivotIndex = left; /*updated left or right is the pivot index*/
return pivotIndex;
}
How do you veterans handle the duplicate values ?
partition()
needs to be amended so really cannot discuss how to handle it. – chux Apr 26 '16 at 22:25