算法 第四版 2.3.18

package Cap2_3;

import edu.princeton.cs.introcs.StdDraw;
import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;
import Cap2_1.SortCompare;
import Cap2_1.SortTemplate;

public class Quick3way extends SortTemplate{

	public static void sort(Comparable[] a){
		StdRandom.shuffle(a);
		sort(a, 0, a.length-1);
	}
	public static void sort(Comparable[] a, int lo, int hi){

		if(hi <= lo) return;
		int lt = lo, i = lo + 1, gt = hi;
		Comparable v = a[lo];
		while(i <= gt){

			int cmp = a[i].compareTo(v);
			if      (cmp<0) exch(a, i++, lt++);
			else if (cmp>0) exch(a, i, gt--);
			else            i++;
		}
		sort(a, lo, lt-1);
		sort(a, gt+1, hi); //重复部分不用管了;	
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StdDraw.setXscale(0, 3);
		StdDraw.setYscale(-0.1, 5);
		int cnt=0;
		for(int N=100;N<=10000;N*=10){
			double t1 = SortCompare.timeRandomInput("Quick3way", N, 1000);
			double t2 = SortCompare.timeRandomInput("Quick", N, 1000);
			
			StdOut.println(t1+ " " + t2);
			StdDraw.setPenColor(StdDraw.RED);
			StdDraw.filledRectangle(0.5+cnt, t1/2, 0.3, t1/2);
			
			StdDraw.setPenColor(StdDraw.BLUE);
			StdDraw.filledRectangle(0.5+cnt, t2/2, 0.3, t2/2);
			cnt++;
		}
	}

}
算法 第四版 2.3.18_第1张图片

你可能感兴趣的:(算法 第四版 2.3.18)