快速排序 Java的实现与思路

tech2022-12-06  90

快速排序与归并排序类似,只不过他是在不断的寻找数组中的基准位置(基准位置左边的元素比基准小右边的比基准大),在以基准为中点对左和右两个数组去找基准直到当前层的数组达到最小,那么此时数组每个位置都满足基准位置那么数组已经排序成功。

代码:

public class suanfa4 { public static void main(String[] args) { int[] ints = {1,1,5,3,2,5,4,8}; quicklySort(ints,0,ints.length-1); for (int anInt : ints) { System.out.println(anInt); } } public static void quicklySort(int[] temp,int low,int hight){ if (low<hight){ int index = marge(temp,low,hight); quicklySort(temp,low,index-1); quicklySort(temp,index+1,hight); } } private static int marge(int[] temp, int low, int higth) { int key = temp[low]; while(low<higth){ while (temp[higth]>=key&&low<higth) higth--; temp[low] = temp[higth]; while (temp[low]<=key&&low<higth) low++; temp[higth] = temp[low]; } temp[low]=key; return low; } }
最新回复(0)