Prompt
Write a function that takes in an array of integers and returns a sorted version of that array. Use the Quick Sort algorithm to sort the array.
Sample Input
array = [8, 5, 2, 9, 5, 6, 3]
Sample Output
[2, 3, 5, 5, 6, 8, 9]
Solution
class Program {
// Best & Average: O(nlogn) time | O(logn) space
// Worst: O(n^2) time | O(logn) space
public static int[] quickSort(int[] array) {
quickSortHelper(array, 0, array.length - 1);
return array;
}
public static void quickSortHelper(int[] array, int startIdx, int endIdx) { //A
if(startIdx >= endIdx) { //B
return ;
}
int pivotIdx = startIdx;
int leftIdx = startIdx + 1;
int rightIdx = endIdx;
while (leftIdx <= rightIdx) {//C
if (array[leftIdx] > array[pivotIdx] && array[rightIdx] < array[pivotIdx]) {
swap(leftIdx, rightIdx, array);
}
if (array[leftIdx] <= array[pivotIdx]) {
leftIdx += 1;
}
if (array[rightIdx] >= array[pivotIdx]) {
rightIdx -= 1;
}
}
swap(pivotIdx, rightIdx, array);
boolean leftSubArratIsSmaller = rightIdx - 1- startIdx < endIdx - (leftIdx);//D
if(leftSubArratIsSmaller){
quickSortHelper(array, startIdx, rightIdx - 1 );
quickSortHelper(array, leftIdx, endIdx);
} else {
quickSortHelper(array, leftIdx, endIdx);
quickSortHelper(array, startIdx, rightIdx - 1 );
}
}
public static void swap(int i, int j, int[] array) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
# A
因为递归每一次的返回值,所以最好是void
# B
- 下次再敲一遍代码,体会一下这里的符号
# C
- 下次再敲一遍代码,体会一下这里的符号
# D
对于空间复杂度的优化,这样再最坏时间复杂度的情况,空间复杂度位1.