首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

排序算法(二):插入排序 Java 實現與最佳/最壞情況分析

     編輯:關於C語言

算法思想

  1. 從第 2 個元素起,將當前元素插入已排序的左側部分。
  2. 從右向左比較,若當前元素較小則右移左側元素,直到找到合適位置插入。

Java 實現

[java]
package com.robert.paixu;

public class InsertSortAlgorithm {
    public static void main(String[] args) {
        int[] arrays = {4,6,9,2,0,1,-5,10,-20,100,20,15};
        insertSort(arrays);
        display(arrays);
    }

    private static void insertSort(int[] arrays) {
        for (int i = 0; i < arrays.length; i++) {
            int currentIndex = i;
            int preIndex = i - 1;
            while (currentIndex != 0 && preIndex >= 0) {
                if (arrays[currentIndex] < arrays[preIndex]) {
                    swap(arrays, currentIndex, preIndex);
                    currentIndex--;
                } else break;
                preIndex--;
            }
        }
    }

    private static void swap(int[] arrays, int i, int j) {
        int temp = arrays[i];
        arrays[i] = arrays[j];
        arrays[j] = temp;
    }

    private static void display(int[] arrays) {
        for (int v : arrays) System.out.print(v + " ");
    }
}

複雜度分析

  • 最好:O(n)(數組已有序,內層循環立即 break)。
  • 最壞:O(n²)(數組逆序,每次插入都要移到最前)。
  • 平均:O(n²)。
  • 空間:O(1),原地排序。
  • 穩定性:穩定(相等元素不交換順序)。

優化方向

  • 二分查找插入位置(O(n log n) 比較,但移動仍 O(n²))。
  • 希爾排序(分組插入,大幅減少移動次數)。

適用場景

數據量小、近乎有序、要求穩定排序的場合。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved