Insertion Sort(插入排序)
2017-03-21 22:03
260 查看
基本思路:
当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。即逐个与左边元素进行比较。
时间复杂度分析
当倒置的数量很少时,插入排序很快。设想,当数组本身有序时,那么每个数只要和它左边的数进行比较就可,总共需要n-1次。
当数组是降序排列的并且不存在重复值,每个元素都移动到数组开头,那么需要进行1/2N^2次比较和1/2N^2次交换。
总结
当大多数有序的情况下使用插入排序更加迅速。
当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。即逐个与左边元素进行比较。
import java.util.Scanner; public class Insertion { public static void sort(Comparable[] a)//排序,依次与前面有序的串比较,若小于则向前移动,直到前面有序为止。 { for(int i=1;i<a.length;i++) { for(int j=i;j>0;j--) { if(less(a[j],a[j-1])) { exch(a,j,j-1); } } } } private static void exch(Comparable[] a, int x, int y) {//交换 Comparable temp = a[x]; a[x] = a[y]; a[y] = temp; } private static boolean less(Comparable x, Comparable y) {//比较大小 return x.compareTo(y) < 0; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); int N = cin.nextInt(); Integer[] array = new Integer ; for(int i=0;i<array.length;i++) { array[i] = cin.nextInt(); } sort(array); for(int i=0;i<array.length;i++) { System.out.print(array[i]+" "); } } }
时间复杂度分析
当倒置的数量很少时,插入排序很快。设想,当数组本身有序时,那么每个数只要和它左边的数进行比较就可,总共需要n-1次。
当数组是降序排列的并且不存在重复值,每个元素都移动到数组开头,那么需要进行1/2N^2次比较和1/2N^2次交换。
总结
当大多数有序的情况下使用插入排序更加迅速。
相关文章推荐
- 插入排序 Insertion sort
- 经典排序算法 – 插入排序Insertion sort
- 结合归并排序和插入排序 Merge with Insertion Sort
- 插入排序insertionSort
- 排序算法---插入排序(Insertion Sort)
- 插入排序(insertion_sort)详解
- 插入排序(INSERTION SORT)
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- Insertion Sort List——链表的插入排序
- Aizu ALDS1_1_A Insertion Sort(插入排序)
- 算法-插入排序(Insertion Sort)
- LeetCode 147 Insertion Sort List(链表插入排序)
- Insertion Sort List(单链表插入排序)
- InsertionSort(插入排序)
- 从VB来看-InsertionSort(VB插入排序)
- 插入排序 (Insertion Sort)
- PAT 1098. Insertion or Heap Sort (25) 堆排序和插入排序
- 经典排序算法 – 插入排序Insertion sort
- 【DS】排序算法之插入排序(Insertion Sort)
- 【算法导论学习-001】插入排序(InsertionSort)