/**
* @author Ye..
* 插入排序
* 實作原理:
* 1。把所有的元素分為兩組,已經排序的和未排序的
* 2。找到未排序的組中的第一個元素,向已經排序的組中進行插入
* 3。倒叙周遊已經排序的元素,依次和待插入的元素進行比較,直到找到第一個元素小于等于待插入元素,那麼就把待插入元素放到這個位置,其他的元素向後移一位。
*/
public class Insert {
public static void main(String[] args) {
Integer[] attr = {4, 5, 9, 8, 2, 1, 7, 6, 3, 10};
for (int i = 1; i < attr.length; i++) {
for (int j = i; j > 0; j--) {
if (greater(attr[j], attr[j - 1])) {
break;
} else {
exch(attr, j, j - 1);
}
}
}
System.out.println(Arrays.toString(attr));
}
/**
* 比較大小
*/
public static boolean greater(Comparable a, Comparable b) {
return a.compareTo(b) > 0;
}
/**
* 元素交換位置
*/
public static void exch(Comparable[] c, int a, int b) {
Comparable comparable = c[a];
c[a] = c[b];
c[b] = comparable;
}
}