JAVA的插入排序
时间复杂度:O(N^2)
public class Sort<T extends Comparable<T>> {
private T[] elemnet;
public Sort(T[] elemnet, int len) {
this.elemnet = elemnet;
}
public void insertSort() {
int i;
int j;
for (i = 1; i < elemnet.length; i++) {
T tmp = elemnet[i];
for (j = i - 1; j >= 0; j--) {
if (elemnet[j].compareTo(tmp) > 0) {
elemnet[j + 1] = elemnet[j];
} else {
break;
}
}
elemnet[j + 1] = tmp;
}
}
public static void main(String[] args) {
Integer[] arr = {4, 5, 2, 1, 8, 0, 9};//优化
Sort<Integer> sort = new Sort<>(arr, arr.length);
sort.insertSort();
System.out.println(Arrays.toString(arr));
}
}