package com.gem.JavaHomeworkDay5;
public class QuickSort {
public static void main(String[] args) {
int[] arr = new int[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 100);
System.out.print(arr[i] + " ");
}
System.out.println();
quickSort(arr,0,arr.length - 1);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static int divideArr(int[] arr,int start,int end){
//每次都以最左边的元素作为基准值
int base = arr[start];
//start一旦等于end,就说明左右两个指针合并到了同一位置,可以结束此轮循环。
while(start < end){
while(start < end && base <= arr[end]){
end--;
}
//右边的数小于基准值时,和基准值换位
if(start < end){
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
start++;
}
//从右边开始向左循环,直到基准值小于左边的,换位
while(start < end && arr[start] <= base){
start++;
}
if(start < end){
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
end--;
}
}
return end;
}
public static void quickSort(int[] arr,int start,int end){
if(start > end){
return;
}
else{
int position = divideArr(arr,start,end);
quickSort(arr,start,position - 1);
quickSort(arr,position + 1,end);
}
}
}
快速排序
最新推荐文章于 2021-11-19 16:57:43 发布