1. 程式人生 > >直接插入排序的Java實現、效能分析以及適用場景

直接插入排序的Java實現、效能分析以及適用場景

1.直接插入排序的Java實現:

程式碼如下:

package com.zm.testSort;
/**
 * 直接插入排序類
 * @author zm
 */
public class InsertSort {
    public static void getInsertSort(int[] a) {
        if(a == null || a.length == 0) {//判斷陣列是否為空
            System.out.println("該陣列為空!");
            return;
        }
        int n = a.length;//將陣列的長度賦給n是為了防止每次for迴圈中判斷時都呼叫length方法影響效能
int temp;//放於for迴圈外面是為了防止重複建立變數 int j; for(int i = 1; i < n;i++){//排序的趟數 temp = a[i];//賦給temp是為了防止索引i之前的元素向後移動覆蓋了索引i的元素 j = i-1; for(; j>=0&&a[j]>temp; --j) {//將大於i位置元素的元素向後移 a[j+1] = a[j]; } a[j+1
]= temp;//找到i應該在的位置,將值放置此處 } } public static void main(String[] args) { int[] a = {3, 5, 1, 2, 6, 4, 7, 11, 23, 44, 3, 34}; getInsertSort(a); System.out.print("直接插入排序:"); for(int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } }

2.直接插入排序的效能分析:

時間複雜度:
1. 最好情況:O(n)
2. 平均情況:O(n^2)
3. 最壞情況:O(n^2)
空間複雜度:O(1)
穩定性:穩定(相同元素的相對位置不會改變)

3.適用場景

3.1:當n <= 50時,適合適用直接插入排序和簡單選擇排序,如果元素包含的內容過大,就不適合直接插入排序,因為直接插入排序需要移動元素的次數比較多.

3.2:當陣列基本有序的情況下適合使用直接插入排序和氣泡排序,它們在基本有序的情況下排序的時間複雜度接近O(n).