快速排序的执行流程如下:
- 1.从序列中选择一个轴点元素pivot从最后一个元素向前遍历,一般情况下选择起始点作为privot
- 2.利用pivot将数组分割成2个子数组
- 将小于pivot的元素放在pivot的左侧
- 将大于pivot的元素放在pivot的右侧
- 将等于pivot的元素放在pivot的哪侧都可以,本文选择左侧
- 对子序列进行步骤1和步骤2操作
根据这个流程,我们图解一下:
代码如下:
void quickSort(int[] nums, int start, int end) {
if (start >= end) return;//递归 终止条件
int leftIndex = start;
int rightIndex = end;
int privot = nums[leftIndex];//暂存
while (leftIndex < rightIndex) {
while (leftIndex < rightIndex && nums[rightIndex] >= privot) {//直至找到小于priot的位置
rightIndex--;
}
nums[leftIndex] = nums[rightIndex];
while (leftIndex < rightIndex && nums[leftIndex] < privot) {//直至找到大于于priot的位置
leftIndex++;
}
nums[rightIndex] = nums[leftIndex];
}
nums[leftIndex] = privot;//
quickSort(nums, start, leftIndex - 1);
quickSort(nums, leftIndex + 1,end);
}