如果使用递归实现快速排序。涉及到选取基数和两层while循环
如下是选取基数为左边。则里层while循环应该右边先开始
int target = nums[left];
while(start<end){
while(left<right && nums[end]>target){
end--;
}
while(left<right && nums[start]<=target){
start++;
}
}
其实都可以。看你基数选取的位置
同理也可以选取右边为基数位置 里层while循环左边开始
int target = nums[right];
while(start<end){
while(left<right && nums[start]<=target){
start++;
}
while(left<right && nums[end]>target){
end--;
}
}
完整代码:
基数选左边:
public class QuickSort {
public void quickSort(int[] nums, int left, int right) {
if (left < right) {
int partition = partition(nums, left, right);
quickSort(nums, left, partition - 1);
quickSort(nums, partition + 1, right);
}
}
public int partition(int[] nums, int left, int right) {
int start = left;
int end = right;
int target = nums[left];
while (start < end) {
while (start < end && nums[end] > target) {
end--;
}
while (start < end && nums[start] <= target) {
start++;
}
swap(nums, start, end);
}
swap(nums, left, end);
return end;
}
private void swap(int[] nums, int start, int end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
}
基数选右边:
public class QuickSort {
public void quickSort(int[] nums, int left, int right) {
if (left < right) {
int partition = partition(nums, left, right);
quickSort(nums, left, partition - 1);
quickSort(nums, partition + 1, right);
}
}
public int partition(int[] nums, int left, int right) {
int start = left;
int end = right;
int target = nums[right];
while (start < end) {
while (start < end && nums[start] < target) {
start++;
}
while (start < end && nums[end] >= target) {
end--;
}
swap(nums, start, end);
}
swap(nums, right, start);
return start;
}
private void swap(int[] nums, int start, int end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
}