直接插入排序

來源:互聯網
上載者:User

標籤:nbsp   樣本   eth   直接插入排序   class   記錄   img   複雜   移動   

插入排序—直接插入排序(Straight Insertion Sort)

基本思想:

將一個記錄插入到已排序好的有序表中,從而得到一個新,記錄數增1的有序表。即:先將序列的第1個記錄看成是一個有序的子序列,然後從第2個記錄逐個進行插入,直至整個序列有序為止。

要點:設立哨兵,作為臨時儲存和判斷數組邊界之用。

直接插入排序樣本:

 

如果碰見一個和插入元素相等的,那麼插入元素把想插入的元素放在相等元素的後面。所以,相等元素的前後順序沒有改變,從原無序序列出去的順序就是排好序後的順序,所以插入排序是穩定的。

演算法的實現:

package method;/** * Created by Administrator on 2017/10/10. */public class InsertSort {    public static void print(int[] a, int n ,int i){        System.out.print(i);        System.out.print(":");        for(int j= 0; j<n; j++){            System.out.print(a[j]);            System.out.print(" ");        }        System.out.println();    }    public static void InsertSort(int[] arr){        int i, j;        int n = arr.length;        int target;        //假定第一個元素被放到了正確的位置上        //這樣,僅需遍曆1 - n-1        for (i = 1; i < n; i++){            j = i;            target = arr[i];            while (j > 0 && target < arr[j - 1]){                arr[j] = arr[j - 1];                j--;            }            arr[j] = target;            //列印每趟排序的結果            print(arr,n,i);        }    }    public static void InsertSort1(int[] a, int n){        for(int i= 1; i<n; i++){            //若第i個元素大於i-1元素,直接插入。小於的話,移動有序表後插入            if(a[i] < a[i-1]){                int j= i-1;                //複製為哨兵,即儲存待排序元素                int x = a[i];                //先後移一個元素                a[i] = a[i-1];                //尋找在有序表的插入位置                while( j >=0 && x < a[j]){                    a[j+1] = a[j];                    //元素                    j--;                }                //插入到正確位置                a[j+1] = x;            }            //列印每趟排序的結果            print(a,n,i);        }    }    public static void main(String[] args){        int[] a = {3,1,5,7,2,4,9,6};        //求數組長度        int n =a.length;        System.out.println(n);        //InsertSort(a);        InsertSort1(a,n);        //列印最終結果        print(a,n,n);    }}

結果

8
1:1 3 5 7 2 4 9 6
2:1 3 5 7 2 4 9 6
3:1 3 5 7 2 4 9 6
4:1 2 3 5 7 4 9 6
5:1 2 3 4 5 7 9 6
6:1 2 3 4 5 7 9 6
7:1 2 3 4 5 6 7 9
8:1 2 3 4 5 6 7 9

Process finished with exit code 0

時間複雜度:O(n^2).

其他的插入排序有二分插入排序,2-路插入排序。

直接插入排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.