排序-插入排序

插入排序

插入排序(Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

1.分析

2.代码

public class InsertionSort {
    public static void main(String[] args) {
        int[] a = {10,2,7, 6, 1, 4, 3};
        sort(a);
        print(a);
    }

    static void sort(int[] a) {
        for (int i = 1; i <a.length; i++) {
            for (int j = i; j >0 ; j--) {
                if(a[j]<a[j-1]){
                    swap(a,j,j-1);
                }
            }
        }
    }
 
    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

3.复杂度

最优时间复杂度:O(n)
最坏时间复杂度:O(n2)
平均时间复杂度:O(n2)
空间复杂度:1
稳定性:稳定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值