Appearance
插入排序算法
java
import java.util.Arrays;
/**
* 插入排序算法
* 遍历数组,当遍历之后需要从索引向前遍历,对比相邻的数据,如果顺序不对就交换两个元素
*/
public class Insertion extends SortTemp{
@Override
public void sort(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
/*从当前位置向前遍历*/
for (int j = i; j > 0 && less(a[j],a[j-1]); j--) {
exech(a,j,j-1);
}
}
}
public static void main(String[] args) {
String[] strings = {"b", "a", "g", "d"};
// Arrays.sort(strings);
System.out.println(Arrays.toString(strings));
Insertion insertion = new Insertion();
assert !insertion.isSorted(strings);
insertion.sort(strings);
System.out.println(Arrays.toString(strings));
assert insertion.isSorted(strings);
}
}