public class Quicksort { public static void main(String[] args) { int [] arr={4,2,6,1,5,3,8,7,9,-1}; ksSort(arr,0,arr.length-1); System.out.println(Arrays.toString(arr)); } //递归排序 private static void ksSort(int[] a, int low, int hight){ if(low<hight){ int mid=getMid(a,low,hight);//返回基准下标,基准左边的数都比基准小,右边大 ksSort(a,low,mid-1);//递归排序基准左边的数 ksSort(a,mid+1,hight);//递归排序基准右边的数 } } //排序并且获取基准下标 private static int getMid(int[] a, int low, int hight){ int base=a[low]; while (low!=hight){ //循环一直找到右边比基准小的数然后和基准交换 while (low<hight&&a[hight]>=base){ hight--; } swap(a,low,hight); //循环一直找到左边比基准大的数然后和基准交换 while (low<hight&&a[low]<=base){ low++; } swap(a,low,hight); } return low;//返回low==hight时的下标,也是基准的下标 } //交换 private static void swap(int[] a,int low,int hight){ int temp=a[low]; a[low]=a[hight]; a[hight]=temp; } }
排序--快速排序
最新推荐文章于 2024-09-12 15:56:42 发布