面试题:插入排序

博客详细讨论了如何使用C语言实现插入排序,并针对其效率进行了优化,适合面试准备和学习排序算法。

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

  • 采用插入排序对一组无序元素进行排序

  • 实现代码

void InsertSort(int *arr, int size)//插入排序简单版
{
    if (NULL == arr || size <= 0)
        return;
    for (int idx = 1; idx < size; idx++)
    {
        int start = idx - 1;
        int temp = arr[idx];
        while (start >= 0 && arr[start] > temp)
        {
            arr[start + 1] = arr[start];
            start--;
        }
        arr[start + 1] = temp;//循环出来start已经多减了一个1已经小于0了。
    }
}

上述算法由于在找到插入位置前每个元素都需要比较,因此我们对此进行优化

void Insert_Quck(int *arr, int size)//插入排序优化版
{
    if (NULL == arr || size <= 0)
        return;
    for (int idx = 1; idx < size; idx++)
    {
        int start = idx - 1;
        int left = 0;
        int right = idx;
        int mid = 0;
        int temp = arr[idx];
        while (left < right)//寻找插入位置
        {
            mid = left + ((right - left) >> 1);
            if (arr[idx] > arr[mid])
            {
                left = mid + 1;
            }
            else
                right = mid - 1;
        }
        while (start > left)//start大于寻找的插入位置才需要搬移等于的话相当于插入位置就在前一个需要判断看是否需要交换
        {
            arr[start + 1] = arr[start];
            start--;
        }
        //循环出来start在left的位置上
        if (arr[start] > temp)//同样已解决了插入位置就在start上的问题
        {
            arr[start + 1] = arr[start];
            start--;
        }
        arr[start+1] = temp;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值