您的位置:首页 > 其它

排序三 直接插入排序

2015-03-05 10:27 197 查看
[b]要点[/b]


直接插入排序是一种最简单的插入排序

插入排序:每一趟将一个待排序的记录,按照其关键字的大小插入到有序队列的合适位置里,知道全部插入完成。

在讲解直接插入排序之前,先让我们脑补一下我们打牌的过程。
先拿一张5在手里,

再摸到一张2,比5小,插到5前面,

摸到一张6,嗯,比5大,插到5后面,

摸到一张3,插到2和5之间,

。。。

最后一看,我靠,凑到全是同花顺,这下牛逼大了。

1 import java.util.Random;

2

3 public class InsertSort {

4

5 public void insertSort(int[] list) {

6 // 打印第一个元素

7 System.out.format("i = %d:\t", 0);

8 printPart(list, 0, 0);

9

// 第1个数肯定是有序的,从第2个数开始遍历,依次插入有序序列

for (int i = 1; i < list.length; i++) {

int j = 0;

int temp = list[i]; // 取出第i个数,和前i-1个数比较后,插入合适位置

// 因为前i-1个数都是从小到大的有序序列,所以只要当前比较的数(list[j])比temp大,就把这个数后移一位

for (j = i - 1; j >= 0 && temp < list[j]; j--) {

list[j + 1] = list[j];

}

list[j + 1] = temp;

System.out.format("i = %d:\t", i);

printPart(list, 0, i);

}

}

// 打印序列

public void printPart(int[] list, int begin, int end) {

for (int i = 0; i < begin; i++) {

System.out.print("\t");

}

for (int i = begin; i <= end; i++) {

System.out.print(list[i] + "\t");

}

System.out.println();

}

public static void main(String[] args) {

// 初始化一个随机序列

final int MAX_SIZE = 10;

int[] array = new int[MAX_SIZE];

Random random = new Random();

for (int i = 0; i < MAX_SIZE; i++) {

array[i] = random.nextInt(MAX_SIZE);

}

// 调用冒泡排序方法

InsertSort insert = new InsertSort();

System.out.print("排序前:\t");

insert.printPart(array, 0, array.length - 1);

insert.insertSort(array);

System.out.print("排序后:\t");

insert.printPart(array, 0, array.length - 1);

}

}

直接插入排序之JAVA代码实现

运行结果

排序前: 6 3 3 5 6 3 1 0 6 4

i = 0: 6

i = 1: 3 6

i = 2: 3 3 6

i = 3: 3 3 5 6

i = 4: 3 3 5 6 6

i = 5: 3 3 3 5 6 6

i = 6: 1 3 3 3 5 6 6

i = 7: 0 1 3 3 3 5 6 6

i = 8: 0 1 3 3 3 5 6 6 6

i = 9: 0 1 3 3 3 4 5 6 6 6

排序后: 0 1 3 3 3 4 5 6 6 6

[b]参考资料[/b]

《数据结构习题与解析》(B级第3版)http://www.cnblogs.com/huangxincheng/archive/2011/11/20/2255695.html

[b]相关阅读[/b] 欢迎阅读 程序员的内功——算法 系列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: