In Quicksort algorithm implementation, the partition method is the key to make average performance as O(nlgn). As written in different algorithm textbook, it has different implementations, in many domestic data structure textbook, the 2 pointers move towards each other, accoring to this implementation, it is very hard to deal with duplicated element condition. However, in Leiserson's Introduction to Algorithm, the 2 pointers move in same direction, its performance is really enhanced and the duplicated elements can be handled gracefully as well。
Method 1: choose the last element in array as pivot,the swap loop starts from the first element of array
template<class T>
int partition1(T A[], int p, int q) {
T pivot = A[q];
int i = p-1;
for (int j = p; j < q; j++) {
if (A[j] <= pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[q]);
return i+1;
}
Method 2:choose the first element as pivot, swap loop starts from second element of array
template<class T>
int partition2(T A[], int p, int q) {
T pivot = A[p];
int i = p;
for (int j=p+1; j<=q; j++) {
if (A[j]<=pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i], A[p]);
return i;
}
Method 1: choose the last element in array as pivot,the swap loop starts from the first element of array
template<class T>
int partition1(T A[], int p, int q) {
T pivot = A[q];
int i = p-1;
for (int j = p; j < q; j++) {
if (A[j] <= pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[q]);
return i+1;
}
Method 2:choose the first element as pivot, swap loop starts from second element of array
template<class T>
int partition2(T A[], int p, int q) {
T pivot = A[p];
int i = p;
for (int j=p+1; j<=q; j++) {
if (A[j]<=pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i], A[p]);
return i;
}