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

常見的內部排序算法有:插入排序、希爾排序、選擇排序、冒泡排序、歸併排序、快速排序、堆排序、基數排序等。用一張圖歸納:算法

clipboard.png

插入排序優化

插入排序(英語:Insertion Sort)是一種簡單直觀的排序算法。它的工做原理是經過構建有序序列,對於未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入。插入排序在實現上,一般採用in-place排序(即只需用到O(1)的額外空間的排序),於是在從後向前掃描過程當中,須要反覆把已排序元素逐步向後挪位,爲最新元素提供插入空間。
插入排序和冒泡排序同樣,也有一種優化算法,叫作拆半插入。spa

  1. 算法步驟code

  2. 將第一待排序序列第一個元素看作一個有序序列,把第二個元素到最後一個元素當成是未排序序列。排序

  3. 從頭至尾依次掃描未排序序列,將掃描到的每一個元素插入有序序列的適當位置。(若是待插入的元素與有序序列中的某個元素相等,則將待插入元素插入到相等元素的後面。)ip

2 動圖演示開發

clipboard.png


  1. JavaScript 代碼實現it

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;
}

  1. Python 代碼實現io

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

  1. Go 代碼實現function

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的另外一個版本

public static void insertion_sort(int[] arr){
              for (int i = 1; i < arr.length; i++ ) {
                      int temp = arr[i];
                      int j = i - 1;  
   
                      for (; j >= 0 && arr[j] > temp; j-- ){
                              arr[j + 1] = arr[j];
                      }
                      arr[j + 1] = temp;
              }
      }

8 C#實現

public static void InsertSort(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;
        }
}

但願能夠一塊兒交流技術,有興趣能夠加qq邀請入羣:525331804 全棧技術開發qq羣:581993430

相關文章
相關標籤/搜索