question:
Give a code fragment that sorts an array that is known to consist of items having just two distinct keys.
answer:
//就是三取样切分的简化版
import edu.princeton.cs.algs4.*; public class Quick2way { private static void exch(Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void sort(Comparable[] a, int lo, int hi) { Comparable v = a[lo]; int i = lo + 1, gt = hi; while(i < gt)//一遍循环就行了 { if(less(v,a[i])) exch(a,i,gt--); else i++; } } public static void show(Comparable[] a) { for(Comparable c : a) StdOut.print(c + " "); StdOut.println(); } public static void main(String[] args) { Integer[] a = {1,1,1,2,1,1,2,2,1,1,2,2,2,1,1,1}; sort(a, 0, a.length-1); show(a); } }
原文地址:https://www.cnblogs.com/w-j-c/p/9129454.html
时间: 2024-10-12 16:07:46