Skip to content

Instantly share code, notes, and snippets.

@HaoyangFan
Last active December 29, 2018 03:16
Show Gist options
  • Select an option

  • Save HaoyangFan/01337cc20fa0fee84d70a45cb0608977 to your computer and use it in GitHub Desktop.

Select an option

Save HaoyangFan/01337cc20fa0fee84d70a45cb0608977 to your computer and use it in GitHub Desktop.
Quick Sort Implementation #2 that put logic of partition into a separate function which return partition index
public class QuickSort2 {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers2(int[] A) {
if (A == null || A.length <= 1) return;
quicksort(A, 0, A.length - 1);
}
private void quicksort(int[] A, int start, int end) {
if (start >= end) return;
int idx = parition(A, start, end);
quicksort(A, start, idx - 1);
quicksort(A, idx + 1, end);
}
// first way: initially putting pivot at the end
private void parition(int[] A, int start, int end) {
// here I am using the middle index as the pivot
int mid = start + (end - start) / 2;
int pivot = A[mid];
// move the pivot to the end of subarray
swap(A, mid, end);
int storeIdx = l;
// iterate through subarray [start, end - 1], moving all elements that
// are less than the pivot to the left of i (which is marked by storeIdx)
for (int i = start; i < end; i++) {
if (A[i] < pivot) {
swap(A, i, storeIdx++);
}
}
// swap pivot with A[storeIdx]
swap(A, storeIdx, end);
// Invariant:
// A[start, storeIdx - 1]: elements are less than pivot
// A[storeIdx]: pivot
// A[storeIdx + 1, end]: elements that are greater than or equal to pivot
return storeIdx;
}
// second way initally putting pivot at the beginning
private int partition(int[] A, int start, int end) {
int mid = start + (end - start) / 2;
int pivot = A[mid];
// swap pivot to the front
swap(A, mid, start);
int i = start + 1, j = start + 1;
while (i <= end) {
if (A[i] < pivot) {
swap(A, i, j++);
}
i++;
}
swap(A, start, j - 1);
return j - 1;
}
private void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment