每天多一点算法-插入排序算法

来源:互联网 发布:淘宝上飞跃鞋是真的吗 编辑:程序博客网 时间:2024/06/06 21:06

插入排序算法


定义


插入排序插入即表示将一个新的数据插入到一个有序数组中,并继续保持有序。例如有一个长度为N的无序数组,进行N-1次的插入即能完成排序;第一次,数组第1个数认为是有序的数组,将数组第二个元素插入仅有1个有序的数组中;第二次,数组前两个元素组成有序的数组,将数组第三个元素插入由两个元素构成的有序数组中......第N-1次,数组前N-1个元素组成有序的数组,将数组的第N个元素插入由N-1个元素构成的有序数组中,则完成了整个插入排序。



时间复杂度


O(n^2)


代码


public class Insertsort {public void sort(int[] a) {// int first = a[0];for (int i = 1; i < a.length; i++) {for (int j = 0; j < i; j++) {if (a[i] <= a[j]) {int temp = a[i];changeSort(a, j, i);a[j] = temp;break;}}}}public void changeSort(int[] a, int start, int end) {for (int i = end; i >= start; i--) {if (i < 1)break;a[i] = a[i - 1];}}public static void main(String[] args) {int[] a = { 10, 5, 3, 4, 1, 6, 7, 9, 8, 10 };System.out.println("排序前 : ");print(a);long start = System.currentTimeMillis();new Insertsort().sort(a);//new Insertsort().changeSort(a, 0, 1);long end = System.currentTimeMillis();System.out.println("排序后 : ");print(a);System.out.println("耗时 : " + (end - start));}public static void print(int[] datas) {for (int i = 0; i < datas.length; i++) {System.out.print(datas[i] + " ");}System.out.println("");}}

输出


排序前 : 10 5 3 4 1 6 7 9 8 10 排序后 : 1 3 4 5 6 7 8 9 10 10 耗时 : 0


上面的V1.0版好像不太符合擦入排序的描述。修改如下:


public class Insertsort {// public void sort(int[] a) {// // 升序排列// for (int i = 1; i < a.length; i++) {// for (int j = 0; j < i; j++) {// if (a[i] <= a[j]) {// int temp = a[i];// changeSort(a, j, i);// a[j] = temp;// break;// }// }// }//// }////public void changeSort(int[] a, int start, int end) {//for (int i = end; i >= start; i--) {//if (i < 1)//break;//a[i] = a[i - 1];//}//}public void sort2(int[] data) {if (data == null || data.length == 0) {return;}int[] temp = new int[data.length];for (int i = 0; i < data.length; i++) {int d = data[i];insertToTemp(temp, d, i);}print(temp);}// 根据升序擦入到数组中private void insertToTemp(int[] temp, int d, int index) {if (index == 0) {temp[index] = d;return;}if (d > temp[index - 1]) {temp[index] = d;return;}int start = -1;// 找到d应该放入的位置,为了遵循升序排序,d应该找到比它大的数,该位置原来的数要后移,然后将d放入该位置,for (int i = 0; i < index; i++) {if (d <= temp[i]) {start = i + 1;break;}}if (start == -1)return;for (int i = index; i >= start; i--) {temp[i] = temp[i - 1];}temp[start - 1] = d;}public static void main(String[] args) {int[] a = { 10, 5, 3, 4, 1, 6, 7, 9, 8, 10 };new Insertsort().sort2(a);}public void print(int[] datas) {for (int i = 0; i < datas.length; i++) {System.out.print(datas[i] + " ");}System.out.println("");}}

前人优化了上面这种死板的方式。查看下面文章中的第二种方法,非常新鲜。


http://blog.csdn.net/morewindows/article/details/6665714

0 0
原创粉丝点击