快排核心思想就是:首先在待排序数组中随便选择一个数作为节点(pivot),然后从最后面(high)往左查找比这个节点(pivot)小的数,并且从最前面(low)往右查找比这个节点(pivot)大的数(low),情况1:找到后就把这两个数进行交换,然后接着上面的查找交换直到low等于high,球后将节点(pivot)与low位置处的数进行交换,这样比pivot小的数都在其前面,比pivot大的数就在其后面,然后把数组以pivot分为两半,重复上述操作;情况2:直到low 等于 high都没有找到,就直接交换pivot和low位置的数据,然后同样的将数组以pivot分为两半重复上述操作。
//测试
public static void main(String[] args) {
int[] array = {3,2,3,1,2,4,5,5,6};
sortArray(array);
System.out.println(Arrays.toString(array));
}
public static int[] sortArray(int[] nums) {
int low=0;
int high=nums.length-1;
quick(nums,low,high);
return nums;
}
public static void quick(int[] nums,int low, int high){
int left=low;
int right=high;
if(low>=right){
return;
}
int povint=nums[low];
while(left<right){
//右,找到比povint小的数
while(left<right&&nums[right]>=povint){
right--;
}
//左 找到比povint大的数
while(left<right&&nums[left]<=povint){
left++;
}
//交换
swap(nums,left,right);
}
//left==right相遇
nums[low]=nums[left];
nums[left]=povint;
//递归
quick(nums,low,left-1);
quick(nums,left+1,high);
}
//交换
public static void swap(int[] nums,int left,int right){
if(left<right){
int temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
}
}
运行结果: