快速排序是一个典型的分治算法:和归并排序一样将A[p...r]划分成两部分,A[p...q]和A[q+1...r],但不是对分(q=[(p+r)/2]),而是利用算法基础二:渐增型算法---序列的划分中的PARTITION过程,使得A[p...q]中的元素值小于A[q+1...r]中的元素值。递归地解决A[p...q]和A[q+1...r]后就可省略合并的过程了。
QUICKSORT(A,p,r) if p < r then q <- PARTITION(A,p,r) QUICKSORT(A,p,q-1) QUICKSORT(A,q+1,r)
人们设法控制算法的行为——每次划分随机地在A[p...r]中选取一个元素作为划分基准,以此来获得平均情形。
RANDOMIZED-PARTITION(A,p,r) i <- RANDOM(p,r) exchange A[r] <-> A[i] return PARTITION(A,p,r)
排序过程中调用RANDOMIZED-PARTITION
RANDOMIZED-QUICKSORT(A,p,r) if p < r then q <- RANDOMIZED-PARTITION(A,p,r) RANDOMIZED-QUICKSORT(A,p,q-1) RANDOMIZED-QUICKSORT(A,q+1,r)
算法基础二:渐增型算法---序列的划分 - DarkerG - 博客园 (cnblogs.com)
import java.util.Collections; import java.util.Comparator; import java.util.List; public class LinearList { public static int randmizedPartition(List<Comparable> a, int p, int r, Comparator comp){ int i = p + (int) ((double) (r-p)*Math.random()); Collections.swap(a,i,r);//a[r] <-> a[i] return partition(a,p,r,comp); } public static int partition(List<Comparable> a, int p, int r, Comparator comp){ Comparable x; int i,j; x = a.get(r); i = p-1; for (j=p;j<r;j++){ if (comp.compare(a.get(j),x)<=0){//a[i]<=x i++; Collections.swap(a,i,j); } } Collections.swap(a,i+1,r); return i+1; } }
import java.util.Comparator; import java.util.List; public class Sort { static public void quickSort(List<Comparable> a, int p, int r, Comparator comp){ if (p<r){//结束的条件 int q = LinearList.randmizedPartition(a,p,r,comp); quickSort(a,p,q,comp);//左边的 quickSort(a,q+1,r,comp);//右边的 } } }
import java.util.Comparator; public class Greater implements Comparator<Comparable> { public int compare(Comparable x, Comparable y){ return x.compareTo(y); } }
import java.util.Comparator; public class Less implements Comparator<Comparable> { @Override public int compare(Comparable o1, Comparable o2) { return o2.compareTo(o1); } }
import java.util.*; public class Test { public static void main(String[] args) { Integer a[] = {5,1,9,4,6,2,0,3,8,7},i; String b[] = {"ChongQing","ShangHai","AoMen","TianJin","BeiJing","XiangGang"}; Double c[] = {8.5,6.3,1.7,9.2,0.5,2.3,4.1,7.4,5.9,3.7}; ArrayList<Integer> A = new ArrayList<>(); Vector<String> B = new Vector<>(); LinkedList<Double> C = new LinkedList<>(); for (Integer integer : a) { A.add(integer); } for (String s : b) { B.add(s); } for (Double aDouble : c) { C.add(aDouble); } Sort.quickSort((List) A,0,9,new Less()); Sort.quickSort((List) B,0,5,new Less()); Sort.quickSort((List) C,0,9,new Greater()); System.out.println(A); System.out.println(B); System.out.println(C); } }