package Cap2_1;
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++){
for(int j=i;j>0 && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
}
}
public static void exch(Comparable[] a, int i, int j){
drawSort(a, i, j);
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
// drawSort(a, i, j);
StdDraw.pause(100);
StdDraw.clear();
}
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
int N=100;
Integer[] a = new Integer[N];
for(int i=0;i<N;i++)
a[i]=i;
StdRandom.shuffle(a);
sort(a);
}
}
算法 第四版 2.1.18 可视轨迹
最新推荐文章于 2021-09-08 10:53:37 发布