排序算法之直接插入排序

来源:互联网 发布:js触发按钮点击事件 编辑:程序博客网 时间:2024/05/22 04:29

时间复杂度:平均O(n²)  最好O(n)  最坏O(n²)

空间复杂度:O(1)

稳定性:稳定

特点:大部分已有序时较好

public class InsertSort {public static void main(String[] args) {int[] a = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };insertSort(a);for (int n : a) {System.out.print(n + " ");}}public static void insertSort(int[] a) {if (a == null) {return;}int i, j, temp;int l = a.length;for (i = 1; i < l; i++) {j = i;temp = a[i];if (temp < a[j - 1]) {while (j > 0 && temp < a[j - 1]) {a[j] = a[j - 1];j--;}a[j] = temp;}}}}


0 0
原创粉丝点击