- 思路:先得到一个基准数,两个指针,头指针和尾指针,基准值设为索引为0的值,pre为 第二个值的索引,last为最后一个值的索引
- 从pre的值开始比较,如果比基准值小,指针移动,否则(比基准值大),那么就和last的值交换位置,last索引移动
- 循环执行,直到pre和last相遇。pre之前的值比基准值小,last之后的值比基准值大
- 把基准值和pre索引的值交换
- 把头-基准值的值按递归排序
- 把基准值-尾的值按递归排序
public class Demo { public static void main(String[] args) { int[] arr = CreatArray.getArr(10, 10, 80); System.out.println(Arrays.toString(arr)); sortArray(arr); System.out.println(Arrays.toString(arr)); } private static void sortArray(int[] arr) { int low = 0; int high = arr.length-1; sortArr(arr,low,high); } private static void sortArr(int[] arr,int low,int high) { if(low<high) { int index = partition(arr, low, high); sortArr(arr, index + 1, high); sortArr(arr, low, high - 1); } } public static int partition(int[] arr,int low,int high){ int k = arr[low]; int pre = low +1; int last = high; while (pre<last){ if(arr[pre]< k){ pre++; }else { int tem = arr[pre]; arr[pre] = arr[last]; arr[last] = tem; last--; } } int t = arr[pre]; arr[pre] = arr[low]; arr[low] = t; return pre; } }
快速排序2
最新推荐文章于 2022-10-30 14:16:43 发布