快速排序java代码
难点有二:
- 结束递归的条件
- while循环里每一步start和end的值都有变化,所以需要不断判断start和end的大小关系。
public static void quickSort(int[] nums, int left, int right) {
//结束递归条件
if (nums == null || nums.length <= 1 || left >= right) {
return;
}
int start = left, end = right;
//选取pivot值
int key = nums[start];
while (start < end) {
while (start < end && nums[end] >= key) {
end--;
}
if (start < end) {
nums[start] = nums[end];
start++;
}
while (start < end && nums[start] <= key) {
start++;
}
if (start < end) {
nums[end] = nums[start];
end--;
}
}
nums[start] = key;
quickSort(nums, left, start - 1);
quickSort(nums, start + 1, right);
}
```