分治法
O(nlogn)
pivot 基准元素
选定了基准元素以后,我们要做的就是把其他元素当中小于基准元素的都移动到基准元素一边,大于基准元素的都移动到基准元素另一边。
具体如何实现呢?有两种方法:
1.挖坑法
2.指针交换法
用递归, 就是用空间换取时间
void quickSort(int[] arr, int startIndex, int endIndex) {
if (startIndex >= endIndex) {
return;
}
int pivotIndex = partition(arr, startIndex, endIndex);
quickSort(arr, startIndex, pivotIndex - 1);
quickSort(arr, startIndex + 1, endIndex);
}
private int partition(int [] arr, int startIndex, int endIndex){
int pivot = arr[startIndex];
int left = startIndex;
int left = endIndex;
while (left != right) {
while(left < right && arr[right] > pivot) {
right--;
}
while(left < right && arr[left] <= pivot) {
left++;
}
if(left < right) {
swap(left, right);
}
}
//pivot和指针重合点交换
swap(left, pivot)
return left;
}