您的位置:首页 > 编程语言 > Java开发

java算法之直接插入排序

2017-08-05 21:54 183 查看
基本思想:

将一个记录插入到已排序好的有序数组中,从而得到一个新的有序数组,记录数增1的有序数组。即:先将数组的第1个记录看成是一个有序的子数组,然后从第2个记录逐个进行插入,直至整个数组有序为止。

代码

public class InsertSort {

public static void insertSort(int[] array) {

int temp;

for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}

public static void main(String[] args) {
int[] a = new int[] { 49, 38, 65, 97, 76, 13, 27, 50 };
insertSort(a);
for (int i : a)
System.out.print(i + " ");
}
}


时间复杂度

O(n^2)—最坏

O(n^2)—平均

O(n) ——最好
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java算法 插入排序