原理:
快速排序也是分治法思想的一种实现,他的思路是使数组中的每个元素与基准值(Pivot,通常是数组的首个值,A[0])比较,数组中比基准值小的放在基准值的左边,形成左部;大的放在右边,形成右部;接下来将左部和右部分别递归地执行上面的过程:选基准值,小的放在左边,大的放在右边。。。直到排序结束。
步骤:
1.找基准值,设Pivot = a[0]
2.分区(Partition):比基准值小的放左边,大的放右边,基准值(Pivot)放左部与右部的之间。
3.进行左部(a[0] - a[pivot-1])的递归,以及右部(a[pivot+1] - a[n-1])的递归,重复上述步骤。
/** * Created by Administrator on 2017-05-15. */public class Test { /** * @param args */ public static void main(String[] args) { Integer[] integer = {8,12,6,9,11,16,78,2}; Test.quick(integer); for(int i : integer){ System.out.print(i+" "); } } //8 12 6 9 11 public static int getMiddle(Integer[] integer,int low ,int high){ //取第一个数为中值 int temp = integer[low]; while(low < high){ while(low < high && temp < integer[high]){ high --; } //将比中值大的数移到最左边 integer[low] = integer[high]; integer[high] = temp ; while(low < high && temp > integer[low]){ low ++; } integer[high] = integer[low]; integer[low] = temp; } return low; } public static void quick(Integer[] integer){ if(integer.length > 0){ quickSort(integer,0,integer.length-1); } } public static void quickSort(Integer[] integer,int low ,int high){ if(low < high){ int middle = getMiddle(integer,low,high); quickSort(integer,low,middle-1); quickSort(integer,middle+1,high); } }}
来源:https://www.cnblogs.com/guxia/p/6842935.html