JavaScript ,Python,java,C#,Go系列算法之【插入排序篇】 插入排序

常见的内部排序算法有:插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。用一张图概括:

插入排序(英语:Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

插入排序和冒泡排序一样,也有一种优化算法,叫做拆半插入。

 

1. 算法步骤

1.将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。

2.从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)

 

 2、动图演示

 

JavaScript ,Python,java,C#,Go系列算法之【插入排序篇】
插入排序

 

 JavaScript ,Python,java,C#,Go系列算法之【插入排序篇】
插入排序

 

 

3、JavaScript 代码实现

function insertionSort(arr) {

    var len = arr.length;

    var preIndex, current;

    for (var i = 1; i < len; i++) {

        preIndex = i - 1;

        current = arr[i];

        while(preIndex >= 0 && arr[preIndex] > current) {

            arr[preIndex+1] = arr[preIndex];

            preIndex--;

        }

        arr[preIndex+1] = current;

    }

    return arr;

}

 

4. Python 代码实现

def insertionSort(arr):

    for i in range(len(arr)):

        preIndex = i-1

        current = arr[i]

        while preIndex >= 0 and arr[preIndex] > current:

            arr[preIndex+1] = arr[preIndex]

            preIndex-=1

        arr[preIndex+1] = current

    return arr

 

5、Go 代码实现

func insertionSort(arr []int) []int {

        for i := range arr {

                preIndex := i - 1

                current := arr[i]

                for preIndex >= 0 && arr[preIndex] > current {

                        arr[preIndex+1] = arr[preIndex]

                        preIndex -= 1

                }

                arr[preIndex+1] = current

        }

        return arr

}

6 、Java实现

 public static void insertion_sort( int[] arr )

{

    for( int i=0; i<arr.length-1; i++ )

    {  

        for( int j=i+1; j>0; j-- )

        {

            if( arr[j-1] <= arr[j] )

                break;

            int temp = arr[j];

            arr[j] = arr[j-1];

            arr[j-1] = temp;

        }

    }

}

7 、Java的另一个版本

        // arr[i] 插入到arr[0]...arr[i - 1]

      public static void insertion_sort(int[] arr)

      {

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

          {

                       int temp = arr[i];

                      int j = i - 1; 

       //如果将赋值放到下一行的for循环内, 会导致在第13行出现j未声明的错误

                       for (; j >= 0 && arr[j] > temp; j-- )

             {

                              arr[j + 1] = arr[j];

                      }

                      arr[j + 1] = temp;

              }

      }

 

 

8、C#实现

publicstaticvoidInsertSort(double[] data){

        int i, j;

        var count = data.Length;

        for (i = 1 ; i < count ; i++) {

        var t = data[i];

            for(j = i - 1; j >= 0 && data[j] > t; j--)

            data[j + 1] = data[j];

            data[j + 1] = t;

        }

}