public class MyQuickSort {/** * 亲测绝对正确 * * */public static void main(String[] args) {int[] ints = { 4, 9, 3, 10, 2, 0, 8, 1 };int low = 0;int high = ints.length-1;System.out.println("排序前:");for (int i : ints) {System.out.print(i);}System.out.println();System.out.println("排序后:");MyQuickSort sort = new MyQuickSort();sort.fastSort(ints, low, high);for (int i : ints) {System.out.print(i);}}/*快速排序*/private void fastSort(int[] ints, int low, int high) {int middle = 0;if (low < high) {//1,找到第一次比较之后的中间位置middle = doSort(ints, low, high);//2,第一次比较后,middle将数组分成两部分,左边都是比ints[middle]小的,右边都是比ints[middle]大的,//3,middle左边部分进行排序fastSort(ints, low, middle - 1);//4,middle右边部分进行排序fastSort(ints, middle + 1, high);}}private int doSort(int[] ints, int low, int high) {//一般从一个数组的第一个数开始比较int data = ints[low];while (low < high) {//data跟数组最后开始往前比,如果data<ints[high],high往前挪一位;while (data < ints[high] && low < high) {high--;}//交换swap(ints, low, high);//data跟数组最前开始往后比,如果data>ints[low],low往后挪一位;while (data > ints[low] && low < high) {low++;}//交换swap(ints, low, high);}//low=high的时候返回low,即为data在数组中的最终位置return low;}private void swap(int[] ints, int low, int high) {if (low == high) {return;}int temp = ints[low];ints[low] = ints[high];ints[high] = temp;}}-----------------打印结果--------------------排序前:493102081排序后:012348910
java快速排序算法
最新推荐文章于 2020-07-12 17:45:41 发布