插入排序

一、简介

算法:插入排序由N-1趟排序组成。对于p=1到N-1趟,插入排序保证从位置0到位置p上的元素为已排序状态。一般思路:在第p趟,我们将位置p上的元素向左移动直至找到它在前p+1个的正确位置为止。

最坏时间复杂度:O( N^2 )

最好时间复杂度:O( N^2 )

平均时间复杂度:O( N )

二、插入排序操作

三、代码

/*
 * @Author: lsyy
 * @Date: 2020-02-11 16:31:25
 * @LastEditTime: 2020-02-22 17:27:33
 * @LastEditors: Please set LastEditors
 * @Description: 插入排序
 * @FilePath: \insertion sort\Src\main.cpp
 */



#include <iostream>
#include <string>
#include <functional>
#include <queue>
#include <vector>

/**
 * @description: 插入排序算法 时间复杂度O(N^2)
 * @param {type} a 排序数组  
 * @return: null
 */
template < typename Comparable >
void insertionSort(std::vector<Comparable> & a )
{
    for( int i = 1; i < a.size( ); ++i )
    {
        Comparable tmp = a[ i ];
        int j;
        for( j = i; j > 0 && tmp < a[ j-1 ]; --j )
            a[ j ] = a[ j-1 ];
        a[ j ] = tmp;
    }
}

/**
 * @description: 插入排序算法 时间复杂度O(N^2)
 * @param {type} begin 起始位置 end 结尾位置 lessThan 比较大小的函数对象 
 * @return: null
 */
template < typename Iterator, typename Comparator >
void insertionSort( const Iterator & begin, const Iterator & end, Comparator lessThan )
{
    if( begin == end )
        return;
    Iterator j;
    for( Iterator it = begin + 1; it != end; ++it )
    {
        auto tmp = *it;
        for( j = it; j != begin && lessThan( tmp, *( j - 1 ) ); --j )
            *j = *( j - 1 );
        *j = tmp; 
    }
}

/**
 * @description: 插入排序算法 时间复杂度O(N^2)
 * @param {type} begin 起始位置 end 结尾位置
 * @return: null
 */
template < typename Iterator >
void insertionSort( const Iterator & begin, const Iterator & end )
{
    insertionSort( begin, end, std::less<decltype(*begin)>{} );
}

class Comparator
{
public:
    bool operator ()( int & val1, int & val2 )
    {
        return val1 > val2;
    }
};

int main( )
{
    int a[] = {1,8,7,5,90,8,4,2,7,6};
    std::vector<int> iv(a,a+sizeof(a)/sizeof(int));
    insertionSort( iv.begin( ), iv.end( ) ,Comparator{ } );

    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值