算法 第四章 2.1.32

package Cap2_1;

import Cap1.Stopwatch;
import edu.princeton.cs.introcs.StdDraw;
import edu.princeton.cs.introcs.StdRandom;

public class Insertion extends sortTemplate{
	public static void sort(Comparable[] a){
		int N = a.length;
		for(int i=1;i<N;i++){
			Comparable temp = a[i];
			int j;
			for(j=i-1;j>=0 && less(temp, a[j]); j--){
				a[j+1] = a[j];
			}
			a[j+1] = temp;

		}
	}
	public static void exch(Comparable[] a, int i, int j){
		Comparable t = a[i];
		a[i] = a[j];
		a[j] = t;
	}
	public static void drawSort(Comparable[] a, int x1, int x2){
		StdDraw.setXscale(-1, a.length+1);
		
		Comparable max=a[0];
		for(int i=1;i<a.length;i++) if(less(max, a[i])) max = a[i];
		StdDraw.setYscale(-2, (Integer)max+1);
		
		for(int i=0;i<a.length;i++){
			int y = (Integer)a[i];
			if(i==x1||i==x2){
				StdDraw.setPenColor(StdDraw.RED);
				StdDraw.filledRectangle(i+0.5, y/2.0, 0.3, y/2.0);
				StdDraw.setPenColor(StdDraw.BLACK);
			}
			else StdDraw.filledRectangle(i+0.5, y/2.0, 0.3, y/2.0);
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StdDraw.setXscale(0, 50);
		StdDraw.setYscale(-5, 10);
		double lastT1=0, lastT2=0;
		for(int i=0;i<50;i++){
			int N=100+i*100;
			Integer[] a = new Integer[N];
			for(int j=0;j<N;j++)
				a[j]=j;
			StdRandom.shuffle(a);
			Integer[] b = a.clone();
			Stopwatch sw = new Stopwatch();
			sort(a);
			double t1 = sw.elapsedTime();
			sw = new Stopwatch();
			Selection.sort(a);
			double t2 = sw.elapsedTime();
			StdDraw.setPenColor(StdDraw.RED);
			StdDraw.line(i-1, lastT1*100, i, t1*100);
			StdDraw.setPenColor(StdDraw.BLUE);
			StdDraw.line(i-1, lastT2*100, i, t2*100);
			
			lastT1 = t1;
			lastT2 = t2;
		}
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值