Any body could help to correct following code of quick sort would be appreciated.
When I run this code I found the items in the collection
are not sorted in ascending order.
//Quick Sort Algorithm
When I run this code I found the items in the collection
are not sorted in ascending order.
//Quick Sort Algorithm
Code:
/**
* Quick sort is a divide and conquer algorithm which relies on a partition
* operation: to partition an array an element called a pivot is selected.
* All elements smaller than the pivot are moved before it and all greater
* elements are moved after it. This can be done efficiently in linear time
* and in-place. The lesser and greater sublists are then recursively sorted.
* Efficient implementations of quick sort (with in-place partitioning) are
* typically unstable sorts and somewhat complex, but are among the fastest
* sorting algorithms in practice.
*
* @param vec as Vector of MyVector type.
* @param left of type int represent left end index of vector.
* @param right of type int represent right end index of vector.
*/
public static void quickSort(MyVector vec,int left,int right){
if(right-left+1<=10){
insertionSort(vec,left,right);
}
else{
medianOf3(vec,left,right);
int leftPtr=partition(vec,left,right);
quickSort(vec,left,leftPtr-1);
quickSort(vec,leftPtr+1,right);
}
}
/**
* medianOf3 helps to sort the elements at left,middle and right of vector.
*
* @param vec as Vector of MyVector type.
* @param left of type int represent left end index of vector.
* @param right of type int represent right end index of vector.
*/
public static void medianOf3(MyVector vec,int left,int right){
int middle = (left+right)/2;
if(((Comparable)vec.elementAt(left)).compareTo(vec.elementAt(middle))>0){
swap(vec,left,middle);
}
if(((Comparable)vec.elementAt(middle)).compareTo(right)>0){
swap(vec,middle,right);
}
if(((Comparable)vec.elementAt(left)).compareTo(vec.elementAt(middle))>0){
swap(vec,left,middle);
}
}
/**
* partition method help the do partition of vector into half where
* one half contains all the elements less than pivot element and other
* half contains all the elements greater than pivot element.
*
* @param vec as Vector of MyVector type.
* @param left of type int represent left end index of vector.
* @param right of type int represent right end index of vector.
* @return index of type int as partition point.
*/
public static int partition(MyVector vec,int left,int right){
Object pivot = vec.elementAt((left+right)/2);
while(true){
while(((Comparable)vec.elementAt(++left)).compareTo(pivot)<0);
while(((Comparable)vec.elementAt(--right)).compareTo(pivot)>0);
if(left>right){
break;
}
else{
swap(vec,left,right);
}
}
return left;
}
Comment