算法学习之排序(1)--插入排序

一.算法描述

一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
1. 从第一个元素开始,该元素可以认为已经被排序
2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
5. 将新元素插入到该位置后
6. 重复步骤2~5


二.时间复杂度

1.最好情况:如果数组本身是排序的,使用插入排序算法,比较次数为n-1,交换次数为0,因此,最好情况下,插入排序的时间复杂度为O(n).
2.最差情况:如果数组本身是逆序的,使用插入排序算法,比较的次数为(1+2+...+n-1=n(n-1)/2),交换次数和比较次数一样,因此,在最差情况下,插入排序的时间复杂度为O(n^2).
3.平均情况:在平均情况下的时间代价是最差情况下的一半,因此,平均情况下,插入排序的时间复杂度也为O(n^2).


三.空间复杂度

  插入排序是in-place的排序,空间复杂度为O(1)。

    


四.C++实现

#include <iostream>
#include "Sort.h"
bool InsertSort(std::vector<int>& Array)
{
    // return false if the array is empty.
    if (Array.empty())
    {
        std::cout << "The size of the Array is empty." << std::endl;
        return false;
    }
    // return the origin array if there are only one element of the array
    if (Array.size() == 1)
    {
        std::cout << "The size of the array is one." << std::endl;
        return true;
    }
    int Size = Array.size();
    for (int Index = 1; Index < Size; Index++)
    {
        int Value = Array[Index];
        int TrueIndex = Index - 1;
        // find the index of the Value
        for (; TrueIndex >=0; TrueIndex--)
        {
            if (Array[TrueIndex] <= Value)
            {
                break;
            }
            Array[TrueIndex + 1] = Array[TrueIndex];
        }
        // put the value to the TrueIndex
        Array[TrueIndex + 1] = Value;
    }
    return true;
}





五.参考文献

[1] Shaffer C A. Practical Introduction to Data Structure and Algorithm Analysis (C++ Edition)[J]. 2002.
[2] 科曼 and 金贵, 算法导论: 机械工业出版社, 2006.
[3] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "算法导论 (影印版)," ed: 北京: 高等教育出版社.
[4]http://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95



版权所有,欢迎转载,转载请注明出处,谢谢微笑



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值