插入排序Insertion Sort
来源:互联网 发布:网络路演 编辑:程序博客网 时间:2024/05/16 15:58
一、插入排序的基本思想
每次将一个待排序的数,插入到一个已排好序的子集合中,直到集合中所有的数都排好序。
集合S = {S0, S1, ... , Sn-1}
1、子集合 S'是一个有序集合,即是说S'中的数都是已经排好序的,待排序的数设置Si,
开始时S' = {S0} 只有一个数,所以它是有序的集合, i = 1,待排序的数从S1开始;
2、将Si 插入到子集合 S' 中,并将S'排序好序,使得S'是有序集合;
3、i 的值加1,执行第2步,直到i 的值 等于 n-1,即最后一个Sn-1也插入了有序集合S'中,排序结束。
例如:
S = [2, 7, 3, 6, 5, 1]
开始时,设置有序集合是[2]:
[2, 7, 3, 6, 5, 1]
第1次,7是待排序的数,把7插入到有序集合[2]:
[2, 7, 3, 6, 5, 1]
则有序变成[2, 7]
第2次,3是待排序的数,把3插入到有序集合[2, 7]:
[2, 3, 7, 6, 5, 1]
则有序变成[2, 3, 7]
第3次,6是待排序的数,把6插入到有序集合[2, 3, 7]:
[2, 3, 6, 7, 5, 1]
则有序变成[2, 3, 6, 7]
第4次,5是待排序的数,把5插入到有序集合[2, 3, 6, 7]:
[2, 3, 5, 6, 7, 1]
则有序变成[2, 3, 5, 6, 7]
第5次,1是待排序的数,把1插入到有序集合[2, 3, 5, 6, 7]:
[1, 2, 3, 5, 6, 7]
则有序变成[1, 2, 3, 5, 6, 7]
集合S的数已经全部插入有序集合中,排序结束。
二、插入排序的java实现
public class InsertionSort { public static void sort(int[] ints){ int lastIndex = ints.length -1; for(int firstIndex = 1; firstIndex <= lastIndex; firstIndex++){ sort(ints, 0, firstIndex); } } /** * 有序集合:S' = { ints[fromIndex], ... , ints[targetIndex - 1] } * ints[targetIndex]:待排序的数 * */ public static void sort(int[] ints, int fromIndex, int targetIndex){ //fromIndex to (targetIndex - 1) has sorted. while(fromIndex < targetIndex){ if(ints[fromIndex] >= ints[targetIndex]){ int immutable = ints[targetIndex]; //找到ints[targetIndex]应该所在的位置, //则将fromIndex, ..., targetIndex - 1, 移到 fromIndex + 1, ..., targetIndex move(ints, fromIndex, targetIndex); ints[fromIndex] = immutable; break; } fromIndex++; } } /** * 将下标位置在fromIndex, ..., toIndex - 1的数, 移到 fromIndex + 1, ..., toIndex * */ private static void move(int[] ints, int fromIndex, int toIndex){ while(fromIndex < toIndex){ ints[toIndex] = ints[--toIndex]; } } public static void main(String[] args){ int[] ints = {2, 7, 3, 6, 5, 1}; System.out.println(Arrays.toString(ints)); sort(ints); System.out.println(Arrays.toString(ints)); }}
...
0 0
- 插入排序(insertion sort)
- insertion sort 插入排序
- 插入排序(Insertion Sort)
- 插入排序 Insertion Sort
- 插入排序Insertion sort
- 插入排序 (Insertion Sort)
- 插入排序Insertion sort
- 插入排序 Insertion Sort
- 插入排序 insertion sort
- 插入排序 insertion sort
- 插入排序Insertion sort
- 插入排序 Insertion sort
- 插入排序 Insertion Sort
- 插入排序-----Insertion Sort
- INSERTION-SORT插入排序
- 插入排序Insertion Sort
- insertion sort(插入排序)
- 插入排序-Insertion sort
- asp.net 学习之路之gridView控件
- apt linux命令简介
- 如何区分Oracle的数据库,实例,服务名,SID
- 高精度减法
- cxf的spring启动测试配置
- 插入排序Insertion Sort
- 2-SAT问题的解法(uva1146)
- git简单使用入门总结
- MVC 模式中正向传值、反向传值
- malloc函数应用
- putty免密码实现自动登录远程主机
- 正负数排序
- [C++11]新特性试用
- 安卓获取星期