/**
* insertion sort
* @author Administrator
* @param <T>
*/
public class InserttionSort<T extends Comparable<T>> {
//由小到大
public void insertsort(T []a){
int pre;
for(int i =0;i<a.length;i++){
T temp = a[i];//i位置的數值
for(pre = i;pre>0 && temp.compareTo(a[pre-1])<0;pre--)
a[pre] = a[pre-1];
a[pre]=temp;
}
}
public static void main(String[] args) {
Integer[] arr={1,4,8,2,4,5,9,0};
InserttionSort<Integer> inserttionSort= new InserttionSort<Integer>();
inserttionSort.insertsort(arr);
for(int i = 0;i<arr.length;i++){
System.out.print(arr[i]);
}
}
}
嵌套循环每一个都花费N次迭代,所以插入排序为O(N^2)