码迷,mamicode.com
首页 > 编程语言 > 详细

《github一天一道算法题》:插入排序

时间:2014-11-03 22:37:59      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:插入排序   算法   

看书、思考、写代码!

/***********************************************
* copyright@hustyangju
* blog: http://blog.csdn.net/hustyangju
* 2014-11-03
* 题目: 插入排序
* 描述: 给定一个数组,按照逐个插入比较的方法得到一个已序数组
* 解题思路:从第一个元素开始,在已序数组上插入下一个元素,可以从已序数组的尾部,也可以从头部逐个比较插入
* 时间复杂度:原数组顺序排好的情况下,时间复杂度最好,为O(n);原数组逆序排好时,时间复杂度最坏,为O(n^2),平均时间复杂度为O(n^2)
* 空间复杂度:只用到一个临时变量,在原数组上排序,空间复杂度为O(1)
************************************************/
#include <iostream>

using namespace std;
template<class type>
class insert_sort
{
public:
    insert_sort(type *p,int num):_p(p),_num(num){}
    ~insert_sort();
    void sort();
    void print();
private:
    type *_p;
    int _num;
};
template<class type>
insert_sort<type>::~insert_sort()
{

}
template<class type>
void insert_sort<type>::sort()
{
    for(int i=1;i<_num;i++)
    {
        int j=i-1;
        type key=_p[i];
        while((j>=0)&&(_p[j]>key))
        {
            _p[j+1]=_p[j];
            j-=1;
        }
        _p[j+1]=key;
    }
}

template<class type>
void insert_sort<type>::print()
{
    for(int i=0;i<_num;i++)
    {
        cout<<*_p<<" ";
        _p++;
    }
     cout<<endl;
}

int main()
{
    float array[5]={5.1,3,6.8,9.1,10};
    int array1[10]={22,8,9,42,2,78,9,33,11,10};
    insert_sort<float> mysort(array,5);
    mysort.sort();
    mysort.print();
    insert_sort<int> mysort1(array1,10);
    mysort1.sort();
    mysort1.print();
    //system("PAUSE");
}

bubuko.com,布布扣

《github一天一道算法题》:插入排序

标签:插入排序   算法   

原文地址:http://blog.csdn.net/hustyangju/article/details/40748247

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!