`
sunwinner
  • 浏览: 202620 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

基础数据结构和算法三:Insertion Sort

阅读更多

As in selection sort, the items to the left of the current index are in sorted order during the sort, but they are not in their final position, as they may have to be moved to make room for smaller items encountered later. The array is, however, fully sorted when the index reaches the right end.

 

Unlike that of selection sort, the running time of insertion sort depends on the initial order of the items in the input. For example, if the array is large and its entries are already in order (or nearly in order), then insertion sort is much, much faster than if the entries are randomly ordered or in reverse order.

 

Time complexity:

 

Insertionsortuses ~N^/4 compares and ~N^2/4 exchanges to sort a randomly ordered array of length N with distinct keys, on the average. The worst case is ~N^2/2 compares and ~N^2/2 exchanges and the best case is N - 1 compares and 0 exchanges.

 

 

Insertion sort works well for certain types of nonrandom arrays that often arise in practice, even if they are huge. For example, as just mentioned, consider what happens when you use insertion sort on an array that is already sorted. Each item is immediately determined to be in its proper place in the array, and the total running time is linear. (The running time of selection sort is quadratic for such an array.) 

public class Insertion {

    // use natural order and Comparable interface
    public static void sort(Comparable[] a) {
        int N = a.length;
        for (int i = 0; i < N; i++) {
            //showGUI(a);
            for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
                exch(a, j, j-1);
              //  showGUI(a);
            }
            assert isSorted(a, 0, i);
        }
        assert isSorted(a);
    }

    // use a custom order and Comparator interface - see Section 3.5
    public static void sort(Object[] a, Comparator c) {
        int N = a.length;
        for (int i = 0; i < N; i++) {
            for (int j = i; j > 0 && less(c, a[j], a[j-1]); j--) {
                exch(a, j, j-1);
            }
            assert isSorted(a, c, 0, i);
        }
        assert isSorted(a, c);
    }

    // return a permutation that gives the elements in a[] in ascending order
    // do not change the original array a[]
    public static int[] indexSort(Comparable[] a) {
        int N = a.length;
        int[] index = new int[N];
        for (int i = 0; i < N; i++)
            index[i] = i;

        for (int i = 0; i < N; i++)
            for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)
                exch(index, j, j-1);

        return index;
    }

   /***********************************************************************
    *  Helper sorting functions
    ***********************************************************************/
    
    // is v < w ?
    private static boolean less(Comparable v, Comparable w) {
        return (v.compareTo(w) < 0);
    }

    // is v < w ?
    private static boolean less(Comparator c, Object v, Object w) {
        return (c.compare(v, w) < 0);
    }
        
    // exchange a[i] and a[j]
    private static void exch(Object[] a, int i, int j) {
        Object swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    // exchange a[i] and a[j]  (for indirect sort)
    private static void exch(int[] a, int i, int j) {
        int swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

   /***********************************************************************
    *  Check if array is sorted - useful for debugging
    ***********************************************************************/
    private static boolean isSorted(Comparable[] a) {
        return isSorted(a, 0, a.length - 1);
    }

    // is the array sorted from a[lo] to a[hi]
    private static boolean isSorted(Comparable[] a, int lo, int hi) {
        for (int i = lo + 1; i <= hi; i++)
            if (less(a[i], a[i-1])) return false;
        return true;
    }

    private static boolean isSorted(Object[] a, Comparator c) {
        return isSorted(a, c, 0, a.length - 1);
    }

    // is the array sorted from a[lo] to a[hi]
    private static boolean isSorted(Object[] a, Comparator c, int lo, int hi) {
        for (int i = lo + 1; i <= hi; i++)
            if (less(c, a[i], a[i-1])) return false;
        return true;
    }

   // print array to standard output
    private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

 

分享到:
评论

相关推荐

    Java数据结构及算法实例:插入排序 Insertion Sort

    插入排序(Insertion Sort)是一种...总的来说,插入排序是一种基础的排序算法,适用于理解排序算法的基本原理和实现。在实际应用中,对于大数据量的排序,通常会选择更高效的算法,如快速排序、归并排序或堆排序等。

    数据结构与算法教程(C++版)实验和课程设计

    - **性能评估**:对不同的数据结构和算法进行时间和空间复杂度的分析,评估其效率。 - **团队合作**:在项目开发过程中,培养团队协作能力,共同完成一个大型项目的设计与实现。 通过本教程的学习,不仅能够掌握...

    Java数据结构和算法

    标题中提到的“Java数据结构和算法”是计算机科学领域中的基础内容,对于学习Java语言的开发者来说尤为重要。数据结构是组织和存储数据的方式,使得数据操作更加高效;算法则是解决问题的一系列步骤。在Java编程中,...

    c#数据结构和算法源码

    在IT领域,掌握数据结构和算法是至关重要的,特别是对于编程语言如C#的开发者来说。数据结构是存储和组织数据的方式,而算法是解决问题或执行任务的特定步骤。本资源"**c#数据结构和算法源码**"提供了一个实践学习的...

    insertion sort

    insertion sort 数据结构基础

    算法分析和数据结构 Python描述版

    - **强大的内置数据结构**:Python提供了一系列内置的数据结构,如列表(list)、元组(tuple)、字典(dict)等,这些数据结构可以直接用于实现复杂的算法和数据结构。 2. **Python在算法实现中的优势**: - **代码...

    JavaScript 数据结构与算法:气泡排序 Bubble Sort、插入排序 Insertion Sort 实作与分析 - 彭彭直播 at 2020/10/13

    JavaScript_資料結構與演算法_氣泡排序_Bubble_Sort、插入排序_Insertion_Sort_實作與分析_-

    数据结构与算法分析(Java英文版)

    《数据结构与算法分析(Java英文版)》是一本介绍如何利用Java语言处理实际问题中的数据结构和算法的专业书籍。本书由Robert Lafore编写,通过丰富的插图和浅显易懂的语言,帮助读者理解并掌握数据结构和算法的核心...

    Java数据结构与算法概述-初级篇.docx

    本文档主要聚焦于初级水平的数据结构与算法的学习,适用于初学者掌握基础概念和技术要点。主要内容包括栈、队列、链表等基本数据结构以及递归的概念,并详细介绍了几种排序算法的实现方式。 #### 一、基本概念 **...

    数据结构与算法-作者Aho

    - **排序算法**:详细讨论了几种常见的排序算法,包括插入排序(Insertion Sort)、选择排序(Selection Sort)、冒泡排序(Bubble Sort)和归并排序(Merge Sort)。每种算法都有其特定的优势和适用场景。 ##### ...

Global site tag (gtag.js) - Google Analytics