插入排序
2017-01-08 10:24
375 查看
插入排序应该是最简单的排序,其原理将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2),是稳定的排序方法。
插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。
给定数组A=(5,2,4,6,1,3),其排序过程如下:
Java代码:
注:代码来自算法导论的Java实现
插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。
给定数组A=(5,2,4,6,1,3),其排序过程如下:
Java代码:
public class InsertionSorter { private InsertionSorter() {} public static void sort(int[] a) { sort(a, 0, a.length); } public static void sort(int[] a, int fromIndex, int toIndex) { for (int j = fromIndex + 1; j < toIndex; j++) { int key = a[j]; // insert a[j] to array a[0..j-1] int i = j - 1; while (i >= 0 && a[i] > key) { a[i + 1] = a[i]; i--; } a[i + 1] = key; } } public static void sort(Object[] a) { sort(a, 0, a.length); } @SuppressWarnings("unchecked") public static void sort(Object[] a, int fromIndex, int toIndex) { for (int j = fromIndex + 1; j < toIndex; j++) { Object key = a[j]; int i = j - 1; while (i >= 0 && ((Comparable)a[i]).compareTo(key) > 0) { a[i + 1] = a[i]; i--; } a[i + 1] = key; } } public static <T> void sort(T[] a, Comparator<? super T> c) { sort(a, 0, a.length, c); } public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) { for (int j = fromIndex + 1; j < toIndex; j++) { T key = a[j]; int i = j - 1; while (i >= 0 && c.compare(a[i], key) > 0) { a[i + 1] = a[i]; i--; } a[i + 1] = key; } } public static void main(String[] args) { int[] a = {3, 2, 5, 1}; sort(a); System.out.println(Arrays.toString(a)); Integer[] a2 = {3, 2, 5, 1}; sort(a2); System.out.println(Arrays.toString(a2)); a2 = new Integer[]{3, 2, 5, 1}; sort(a2, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); System.out.println(Arrays.toString(a2)); } }
注:代码来自算法导论的Java实现
相关文章推荐
- 插入排序
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- Android数据加密之异或加密算法的实现方法
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法