将整个区间分为已排序区间和待排序区间,拿到当前元素插入到当前的有序顺序表中的合适位置.
import java.util.Arrays;
public class Test {
public static void main(String[] args){
int[] arr={9,5,2,7,3,8,1,6,4};
System.out.println(Arrays.toString(insertSort(arr)));
}
public static int[] insertSort(int[] arr){
for(int bound=1;bound<arr.length;bound++){
int tem=arr[bound];
int cur=bound-1;
for(;cur>=0;cur--){
if(arr[cur]>tem){
arr[cur+1]=arr[cur];
}else {
break;
}
}
arr[cur+1]=tem;
}
return arr;
}
}
稳定性:稳定
两个相等的数据,如果经过排序后,排序算法能保证其相对位置不发生变化,则我们称该算法是具备稳定性的排序算法。
插入排序的
最好时间复杂度为O(n),
最坏时间复杂度为O(n^2) 数据逆序
平均时间复杂度为O(n^2)
空间复杂度为O(1)
1.如果当前序列很短,插入排序很高效
2.基本有序的情况下插入排序也很高效