利用递归实现快速排序,选定最有一个数为轴,遍历区间内的数值,通过交换使其左小右大(此时轴的位置就是排序后的位置,不论左右如何变换,此位置相对不变,所以可按此理论递归实现排序)。再分别为其左右两侧边的数字找准位置排序完成。 第一步:假设以最后一位作为轴,记为P,0位置记为i, 可能大于s[p]的倒数第二个位置记为j 第二步:循环数组,小于s[p]放到左边,大于s[p]通过和s[j]交换放到右边 for i <=j ; s[i] < s[p]; i++. 移动i的位置到下一次可进行寻找比s[P]小的数的位置 s[i] >= s[p]; swap(i, j—). s[i]不小区s[p]的数值时,交换i和j位置的数字,将i放到倒数第二个大于s[p]的位置上。因此时s[j]已经是大于s[p]的数值了,j需要—,向前移动一位等待再次放置比s[p]大的数值。 i > j; 如果i已经大于j,说明比s[p]小的数值已经全部找到了。此时swap(i,p)。(注:i==p的时候不必交换,为减少代码判断,swap具备了当两个位置相等是,不交换的功能) 第三步: 递归实现其他位置的定位

package com.ss.sort;import java.util.Arrays;import java.util.concurrent.ThreadLocalRandom;/*** <p>* 快速排序* </P>** @author: zhangss* @since: 2022-05-07**/public class QuickSort {public static void main(String[] args) {// int[] s = {3, 6, 2, 7, 4, 9};for (int i = 0; i < 5_0000; i++) {int[] s = random(10);int[] cs = copy(s);quickSort(s, 0,s.length - 1);comparator(s, cs);// print(cs);// print(s);}}/*** 单轴快速排序* 选定一个轴位置为P, 将<P放到左边, >P放到右边。P位置就排好了* 括号括住的地方就是比P小最后一个位置* )3, 6, 2, 1, 4, 5* i, -, -, -, j, P** s[i]<s[p]; i++* 3), 6, 2, 1, 4, 5* -, i, -, -, j, P** s[i]>s[p]; swap(i, j--)* swap* 3), 4, 2, 1, 6, 5* -, i, -, -, j, P* j--* 3), 4, 2, 1, 6, 5* -, i, -, j, -, P** s[i]<s[p]; i++* 3, 4), 2, 1, 6, 5* -, -, i, j, -, P** s[i]<s[p];i++ i和j相等时,还不确定i位置的数是和p位置的大小,所以不需要再比较一次。* 3, 4, 2), 1, 6, 5* -, -, -, i/j, -, P** s[i]<s[p]; i++* 3, 4, 2, 1), 6, 5* -, -, -, j, i, P** i>j 跳出循环** swap[i,p]; 此时i位置左边数小于s[i],右边数大于s[i]* 3, 4, 2, 1), 5, 6* -, -, -, j, i, P** @param s 随机数组* @param L 左侧位置* @param R 右侧位置*/public static void quickSort(int[] s, int L, int R){if (L >= R || R < 1) {return;}int i = L, j = R-1;for (; i <= j; ) {if (s[i] < s[R]) {i++;} else {swap(s, i, j--);}}swap(s, i, R);// print(s);// System.out.println("右边有序 i:" + (i+1) + "P:" + R);quickSort(s, i+1, R);// System.out.println("左边有序 L:" + L + "R:" + (i-1));quickSort(s, L, i - 1);}public static void swap(int[] s, int a, int b){if(a == b){return;}int temp = s[a];s[a] = s[b];s[b] = temp;}/*** 对数器* @param s* @param cs*/public static void comparator(int[] s, int[] cs){Arrays.sort(cs);for (int i = 0; i < s.length; i++) {if (s[i] != cs[i]) {throw new RuntimeException("错误喽");}}}public static int[] copy(int[] s){int[] cs = new int[s.length];for (int i = 0; i < s.length; i++) {cs[i] = s[i];}return cs;}public static int[] random(int l){int[] s = new int[l];for (int i = 0; i < l; i++) {s[i] = ThreadLocalRandom.current().nextInt(-100, 100);}return s;}public static void print(int[] s){System.out.println(Arrays.toString(s));}}
