只绘制了Insertion sort的排序变化:
Insertion 实现如下:
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.awt.*;
public class Insertion {
public static void sort(Comparable[]a){
//Sort a[] into increasing order.
int N=a.length;
for (int i=1;i<N;i++){
//Insert a[i] among a[i-1],a[i-2],a[i-3]...
// for (int j=i;j>0&&less(a[j],a[j-1]);j--)
// exch(a,j,j-1);
//self
for (int j=i;j>0;j--)
if (!less(a[j],a[j-1]))//一旦不小于表明该元素已经到了合适的位置,不用再和前面的比较,因为前面已经排过序了
break;
else
exch(a,j,j-1);
}
}
public static void showSort(Double[]a){//绘制double类型
Double MAX= Double.MIN_VALUE;
Double MIN= Double.MAX_VALUE;
for (int i=0;i<a.length;i++){
if (a[i]<MIN) MIN=a[i];
if (a[i]>MAX) MAX=a[i];
}
DrawArray(a,0,0,MAX,MIN);//先画第一个
int N=a.length;
for (int i=1;i<N;i++){
//Insert a[i] among a[i-1],a[i-2],a[i-3]...
int j=i;
for (;j>0;j--)
if (!less(a[j],a[j-1]))//一旦不小于表明该元素已经到了合适的位置,不用再和前面的比较,因为前面已经排过序了
break;
else
exch(a,j,j-1);
DrawArray(a,j,i,MAX,MIN);
}
}
public static void DrawArray(Double[]a,int i,int j,Double MAX,Double MIN){
//i是insertion sort被新排序的位置,高亮显示Page253,j是当前位置,i+1到j为黑色,其余位置为灰色
StdDraw.setXscale(-1,a.length+1);
StdDraw.setYscale(MIN-(MAX-MIN)*0.4,MAX+(MAX-MIN)*0.4);
for (int index=0;index<a.length;index++){
if (index<i||index>j)
StdDraw.setPenColor(Color.gray);
else if (index>i&&index<=j)
StdDraw.setPenColor(Color.BLACK);
else //index==i
StdDraw.setPenColor(Color.red);
StdDraw.filledRectangle(index,a[index]/2.0,0.3,a[index]/2.0);
}
long start = System.currentTimeMillis();
while (System.currentTimeMillis()-start<1000);// wait 1s
StdDraw.clear();
}
private static boolean less(Comparable v,Comparable w){
return v.compareTo(w)<0;
}
private static void exch(Comparable[]a,int i,int j){
Comparable t=a[i];a[i]=a[j];a[j]=t;
}
public static void show(Comparable[]a){
//Print the array ,on a sing line.
for (int i=0;i<a.length;i++)
StdOut.print(a[i]+" ");
StdOut.println();
}
public static boolean isSorted(Comparable[]a){
//Test whether the array entries are in order.
for (int i=1;i<a.length;i++)
if (less(a[i],a[i-1])) return false;
return true;
}
}
测试代码:
import edu.princeton.cs.algs4.StdRandom;
public class E2_1_17 {
public static void main(String[]args){
int N=20;
Double[]a=new Double[N];
for (int i=0;i<N;i++)
a[i]= StdRandom.uniform(0.0,10.0);
Insertion.showSort(a);
assert Insertion.isSorted(a);
Insertion.show(a);
}
}
效果: