排序算法之插入排序
插入排序类似于打扑克,取出未排序的一张牌插入到已排序的牌中,取出的一张牌是在已排序好的牌中从后向前查找,直到查找到比当前牌小的那个位置,然后插入进去
示例代码: [9, 1, 8, 3, 6, 2, 7]
[1, 9, 8, 3, 6, 2, 7]
[1, 8, 9, 3, 6, 2, 7]
[1, 3, 8, 9, 6, 2, 7]
[1, 3, 6, 8, 9, 2, 7]
[1, 2, 3, 6, 8, 9, 7]
[1, 2, 3, 6, 7, 8, 9]
public class InsertSort {
public static void sort(int[] arr) {
int n = arr.length;
// 从 1 开始,把 arr[0] 当成一个序列
for (int i = 1; i < n; i++) {
int temp = arr[i];
int j = i;
// 开始判断 index = j-1 的元素是否需要添加到前边的序列当中
if (arr[j - 1] > temp) {
// 交换位置(注意条件)
while (j >= 1 && arr[j - 1] > temp) {
arr[j] = arr[j - 1];
j--;
}
// 直到 arr[j-1] <=temp 的时候停止
if (j != i) {
arr[j] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
}
public static void main(String[] args) {
int[] arr = new int[] { 1, 9, 8, 3, 6, 2, 7 };
sort(arr);
}
}
时间复杂度O(n^2),空间复杂度O(1),稳定排序。
还没有评论,来说两句吧...