排序算法——插入排序(Insertion Sort)

本文详细介绍了插入排序算法的基本原理、伪代码实现及Java代码示例。分析了算法的时间复杂度,并探讨了其适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

排序算法——插入排序(Insertion Sort)

伪代码(Pseudocode):

function INSERTIONSORT(A[0..n-1])
    for i1 to n-1 do
        v ⟵ A[i]
        ji-1
        while j0 and v < A[j] do
            A[j+1] ⟵ A[j]
            jj-1
        A[j+1] ⟵ v 

基本属性(Property):
Input: an array A[0..n-1] of n orderable elements
Output: an array A[0..n-1] sorted in nondeacending order
The size of input: n
Basic operation: key comparison “v < A[j]”
In-place: YES. only requires a constant amount O(1) of additional memory space.
Stable: YES. does not change the relative order of elements with equal keys.

时间复杂度(Time Complexity):
The for loop is traversed n-1 times. In the ith round, the comparison “v < A[j]” is performed i times in the worst case(array A[0..n-1] is sorted in descending order).
Hence, the worst-case running time is
这里写图片描述
In the best case, which is array A[0..n-1] is already a sorted array.
这里写图片描述
In the average case.
这里写图片描述

适用情形(Suitable Situation):
1. Linear time for almost-sorted array.
2. Small array (a couple of hundreds elements).
3. Some clever sorting algorithms perform amost-sorting and then let insertion sort take over.

Java Code:

public class Sort{
    //Insertion sort method
    public static int[] insertionSort(int[] A){
        int i,j,tmp;
        for(i=1;i<A.length;i++){
            tmp=A[i];
            j=i-1;
            while(j>=0 && A[j]>tmp){
                A[j+1]=A[j];
                j--;
            }
            A[j+1]=tmp;
        }
        return A;
    }

    //Test
    public static void main(String[] args){
        int[] A={1,20,14,78,34,76,11,9,100,52};
        int[] sortedA=Sort.insertionSort(A);
        for(int i=0;i<sortedA.length;i++)
            System.out.print(sortedA[i]+" ");
    }
}

运行结果(Result):

1 9 11 14 20 34 52 76 78 100 

写在最后的话(PS):
This is my first time to write blog. I hope it will be helpful. If there are some issues, please comment. I’m very welcome to talk about it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值