您的位置:首页 > 理论基础 > 数据结构算法

【1】数据结构与算法-1 直接插入排序法

2016-09-06 16:39 405 查看
一、直接插入排序法(Straight Insertion Sort)

直接插入排序的基本操作是将一个记录插入到已经排好有序的有序表中,从而得到一个新的、记录数增1的有序表。下面是方法的具体实现:

(1)不断插入给定的数,按照插入排序的方法进行插入:

<span style="font-size:18px;">package com.sort.exe;

import java.util.ArrayList;

public class InsertSort {

static ArrayList<Integer> list=new ArrayList<>();
public void InsertSort(int num){
int index=0;
int size=list.size();
while(index < size){
//如果插入的数比当前要比较的数小,就跳出,直接插入在这个位置
if(num < list.get(index))
break;
index++;
}
list.add(index,num);
}
public static void main(String[] args) {
InsertSort i=new InsertSort();
i.InsertSort(2);
i.InsertSort(1);
i.InsertSort(8);
i.InsertSort(4);
i.InsertSort(11);
i.InsertSort(3);

for(Integer num:list){
System.out.println(num);
}
}

}
</span>
结果是:1 2 3 4 8 11

(2)给定一个数组,使用直接插入排序的思想对其排序

在排序刚开始的时候,把第一个元素当做是排序的记录,当依次插入后面的元素的时候,就获得其插入的位置,然后形成一个新的有序表。

package com.sort.exe;
import org.junit.Test;
/**
* 过程:57 59  68  52进行排序:
*  i=3:temp=52
* ①j=i-1=2:68>52,68往前移一位:57 59 68 68
* ②j--:    59>52,59往前移一位:57 59 59 68
* ③j--:    57>52,52往前移一位,57 57 59 68
* ④temp放在最后的位置:52 57 59 68
* @author WGS
*/
public class InsertSort2 {
@Test
public void insertSort(int[] arrs){
int i,j,temp=0;
for(i=1;i<arrs.length;i++){
temp=arrs[i];
//后面的数大于前面的数,就将大于temp的值整体后移一个单位
//即拿temp(要插入的值)与其后每个值比较,若小于那个值就插入在那个位置+1;不小于就插在最后
for(j=i-1;j>=0 && temp<arrs[j];j--){
arrs[j+1]=arrs[j];
}
//j变成-1的时候,即最后一位比较完毕,此时temp放在最后
arrs[j+1]=temp;
}
}
//测试用例
@Test
public void test(){
int[] a={57,68,59,52};
insertSort(a);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}


参考来源:【http://www.jb51.net/article/70396.htm】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: