Quick Sort
Introduction
Question (LC.464)
Analysis
Code
public class Solution {
public void sortIntegers(int[] A) {
if (A == null || A.length == 0) {
return;
}
quickSort(A, 0, A.length - 1);
}
private void quickSort(int[] A, int start, int end) {
// base case one element just return it
// not always one there can be zero elements
if (start >= end) {
return;
}
// divide
// we just select a random pivot in the middle
// in a way QS is a randomized algorithm
// the expected (averge) runtime is good
// but worst case can happen in a small likelihood
int pivot = A[start + (end - start) / 2];
// need to partition first (unlike merge sort does this in the end)
int left = start, right = end;
while (left <= right) {
// why not <= here? think about worst case [1,1,1,1,1]
if (A[left] < pivot) {
left++;
} else if (A[right] > pivot) {
right--;
} else {
int temp = A[left];
A[left] = A[right];
A[right] = temp;
left++;
right--;
}
}
// conquer
// QS(A[start...right])
// (cause to break the while loop left&right have to cross each other)
quickSort(A, start, right);
quickSort(A, left, end);
// merge
// we already did this in partition
}
}With Simple Partition
Conclusion
Last updated