《Java算法与数据结构》
时间 复杂度:
从下标为1的元素开始开始选择合适位置拆入因为下标
5 4 3 2 1
-------------------------
temp=a[i]记录要插入的值
j=i;// j的作用是当前值与 用于比较 a[0]--- a[j-1]
比较条件 j>0 temp<a[j-1] 则向右移动
j--
a[j]=temp;
-------------------------------------
* a[0]-->a[1]
5 [4] 3 2 1 -----> 5 5 3 2 1 ---a[0]=temp =4 ---> a[0 ]=4 ----> 45 3 2 1
第一轮
i=1
temp=a[i]=a[1]=4 , 5| [4] 3 2 1
j=i=1;
a[j]=a[1]<----------a[1]=5
a[0]=4
4 5| 3 2 1
------------------------------------
第二轮
4 5| [3] 2 1
i=2
temp=a[2]=3
j=i=2
a[j] a[2]>a[1]
4 5 |-->[5] 3 2 1
a[1]>a[0]
[ ] 4 | [5] 3 2 1
交换结束 此时j-- =0
a[j=0]=temp=3
第二轮结束后
3 4 5 | 3 2 1
------------------------------------
第3轮
i=3
3 4 5 | [ 2 ] 1
要插入 temp= 2
j=3
----遍历移动前面的的元素找到插入位置
j=3>0 temp =2<a[j-1=2]=5 移动
a[3]=a[2]=5
3 4 5 | [ 5 ] 1
j-- j= 2
----------------
a[j=1=2]=4>temp 移动
3 4 4 | 5 1
j=1>0 temp<a[0] 移动 j-- = > j=0
j=0 不满足移动条件找插入位置
a[j]=temp;
-------------------------------------
第四轮
i=4
排序前: 2 3 4 5 | [1]
temp= a[4]= 1
j=i=4
j>0 ,temp<5
----
移动结束
2 2 3 4 | 5
插入
1 2 3 4 5
代码:
package com;
/**
* Created by zengjx on 2019/3/4.
*/
public class InsertSort {
public static int[] insertSort(int[] array){
if(array==null ||array.length<0){
return null;
}
for(int i=1;i<array.length;i++){
int temp= array[i];
int j=i;
while(j>0&& temp<array[j-1]){
array[j]=array[j-1];
j--;
}
array[j]=temp;
}
return array;
}
public static void print(int[] array) {
if(array==null|| array.length<1){
return;
}
if(array.length>0){
StringBuffer sb= new StringBuffer();
for(int i=0;i<array.length;i++){
sb.append(" "+array[i]);
}
System.out.println(" "+sb.toString());
}
}
}
用例:
package com;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by zengjx on 2019/3/4.
*/
public class InsertSortTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void insertSort() throws Exception {
int[] array= new int[]{9,8,6 ,7 ,7,5,3,4,1,10};
int[] ret= InsertSort.insertSort(array);
InsertSort.print(ret);
}
@Test
public void insertSort2() throws Exception {
int[] array= new int[]{9};
int[] ret= InsertSort.insertSort(array);
InsertSort.print(ret);
}
@Test
public void insertSort3() throws Exception {
int[] ret= InsertSort.insertSort(null);
InsertSort.print(ret);
}
}