直接上代码,看注释就能懂
时间复杂度:
最优O(n),
最坏时间复杂度为 O(n^2) ,
平均时间复杂度为O(n^2) 。
空间复杂度:O(1)。
稳定
package sort;
/**
* @author sunny龙龙哥
*
*/
public class InsertSort {
public static void insertSort(int array[]) {
int i;//这是接下来要插入的数的下标;
for( i = 1;i<=array.length-1;i++) {
int temp = 0;
for(int j = 0;j<i;j++) {
if(array[i]<array[j]) {
temp = array[i];
for(int m = i-1;m>=j;m--) {
array[m+1]=array[m];
if(m==j) {
array[j]=temp;
}
}
}
}
}
}
public static void main(String[] args) {
int a[]= {6 ,1, 2, 7, 9, 3, 4, 5, 10, 8};
insertSort(a);
for (int i : a) {
System.out.print(i+" ");
}
}
}