直接插入排序

本文详细介绍了插入排序算法的基本原理,包括其工作流程、时间复杂度分析及C++实现代码。通过实例展示如何将无序元素逐步插入到已排序部分中,确保整体序列最终达到完全有序状态。

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

转载请注明出处。

假设升序排列n个元素。

1、将序列分为有序区和无序区,排序前,有序区元素个数为1,无序区个数为n-1。

2、将无序区的第一个元素插入到有序区,插入位置通过比较确定,直接插入排序是稳定的排序算法。

3、插入过程中需要向右移动插入位置后的元素。

时间复杂度:

最坏情况下,比较次数为n(n-1)/2,时间复杂度为O(n^{2})。

测试代码:

#include<iostream>
#include<iterator>
using namespace std;

void insertionSort(int list[], int length){
    int temp, index;
    for(int firstOutOfOrder=1; firstOutOfOrder < length; firstOutOfOrder++)
        if(list[firstOutOfOrder] < list[firstOutOfOrder-1])
        {
            temp = list[firstOutOfOrder];
            list[firstOutOfOrder] = list[firstOutOfOrder-1];
            index = firstOutOfOrder-1;
            while(index > 0 && list[index-1] > temp)//find insertion location
            {
                list[index] = list[index-1];
                index--;
                count++;
            }
            list[index] = temp;
        }  
}
int main(){
    ostream_iterator<int> screen(cout, ", ");
    int list[] = {9, 8, 7, 6, 5, 4};
    insertionSort(list, sizeof(list)/sizeof(int));
    copy(list, list+sizeof(list)/sizeof(int), screen);
    cout << endl;
}

参考资料:

百度百科,https://baike.baidu.com/item/插入排序/7214992?fr=aladdin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值