原理阐述:就像打牌一样,拿到手上的是无序的牌,从第二张开始,将牌一张一张与前面的比较,遇到第一个比自己小的,就插在它后面,依次执行到最后一张,结束后,就排好序了
note:
- 不需要考虑后面的,只管与所有前面的比较
- 遇到第一个比自己小的
3 5 2 1
以2为例
3 2 5 1
2 3 5 1
2 3 1 5
2 1 3 5
1 2 3 5
代码实现
package 排序;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Insertion {
public static void sort(Comparable[] a) {
for (int i=1; i<a.length; i++) {
//Comparable buff = a[i];
for (int j=i; j>0 && less(a[j],a[j-1]); j--) {
exch(a,j,j-1);
//StdDraw.show();
StdDraw.clear();
Mydraw(a);
}
}
}
private static boolean less(Comparable x,Comparable y) {
return x.compareTo(y)<0;
}
private static void exch(Comparable[] a, int x, int y) {
Comparable t = a[x];
a[x] = a[y];
a[y] = t;
}
private static void show(Comparable[] a) {
for (int i=0;i<a.length;i++) {
StdOut.print(a[i]);
StdOut.println();
}
}
private static void Mydraw(Comparable[] a) {
int N = a.length;
// //设置画布宽
// StdDraw.setXscale(-1, N+1);
//
// //通过遍历来找到最大y,依据这个值来设定高
// Comparable max=a[0];
// for(int i=1;i<N;i++) if(less(max, a[i])) max = a[i];
// Double max_one = (Double)max+1;
// StdDraw.setYscale(-2, max_one.doubleValue());
for (int i=0; i<N; i++) {
double x = 1.0*i/N;
double y = (double)a[i]/2.0;
double rw = 0.3/N;
double rh = (double)a[i]/2.0;
StdDraw.filledRectangle(x, y, rw, rh);
}
}
private static boolean isSort(Comparable[] a) {
for(int i=0; i<(a.length-1);i++) {
if (!less(a[i],a[i+1]))
return false;
}
return true;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] a = StdIn.readAllDoubles();
Double[] b = new Double[a.length];
for(int i=0; i<a.length;i++) {
b[i] = Double.valueOf(a[i]);
}
int N = a.length;
//设置画布宽
StdDraw.setXscale(-1, N+1);
//通过遍历来找到最大y,依据这个值来设定高
Comparable max=a[0];
for(int i=1;i<N;i++) if(less(max, a[i])) max = a[i];
Double max_one = (Double)max+10;
System.out.println("----------------");
System.out.println(max_one);
System.out.println("----------------");
StdDraw.setYscale(-2, max_one.doubleValue());
//Mydraw(b);
sort(b);
assert isSort(b);
show(b);
}
}