package sort;
public class quickSort {
public static void main(String[] args) {
// int nums[] = {3,5,2,4, 1};
// int[] nums = {1,2,3,4,5};
int[] nums = {5,4,3,2,1};
qSort(nums,0, 4);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
public static void qSort(int[] nums, int start, int end){
if(start >= end)
return;
int i = partition(nums, start, end);
qSort(nums, start, i - 1);
qSort(nums,i + 1, end);
}
public static int partition(int[] nums, int start, int end){
int radix = nums[start];
int low = start;
int high = end;
while (low < high){
//循环终结:找到了一个大的 或 end判断完不符合
while (nums[low] <= radix && low < end)
low++;
while (nums[high] >= radix && high > start)
high--;
if(low < high){
int tmp = nums[low];
nums[low] = nums[high];
nums[high] = tmp;
}else{
int tmp = nums[start];
nums[start] = nums[high];
nums[high] = tmp;
}
}
return high;
}
}
大while循环中的两个while循环条件
while (nums[low] <= radix && low < end) low++;
while (nums[high] >= radix && high > start) high--;
第二个条件没有等号,因为这样数组下标记才不会越界
后面low < high说明还要继续找,否则直接用radix和high交换即可(因为high是比radix小的)