插入排序
插入排序(Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
1.分析

2.代码
public class InsertionSort {
public static void main(String[] args) {
int[] a = {10,2,7, 6, 1, 4, 3};
sort(a);
print(a);
}
static void sort(int[] a) {
for (int i = 1; i <a.length; i++) {
for (int j = i; j >0 ; j--) {
if(a[j]<a[j-1]){
swap(a,j,j-1);
}
}
}
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
3.复杂度
最优时间复杂度:O(n)
最坏时间复杂度:O(n2)
平均时间复杂度:O(n2)
空间复杂度:1
稳定性:稳定