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

插入排序

时间:2015-06-30 20:13:58      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

插入排序

C++代码:

template <typename T>
void SortUtil<T>::insertionSort(vector<T>& data)
{
    int j = 0;
    for (int i = 1; i < data.size(); i++)
    {
        T key = data[i];

        // insert data[i] into the sorted sequence data[0..i-1]
        j = i;
        while (j > 0 && data[j - 1] > key)
        {
            data[j] = data[j - 1];
            j--;
        }

        data[j] = key;
    }
}

测试代码(C++):

void display(vector<int> data)
{
    for (auto& elem : data)
    {
        cout << elem << endl;
    }
}

int main(int argc, char* argv[])
{
    vector<int> data1 { 9, 5, 18, 21, 32, 93, 2 };
    cout << "before sort:" << endl;
    display(data1);
    SortUtil<int>::insertionSort(data1);
    cout << "after sort:" << endl;
    display(data1);
}
        

运行结果:
before sort:
9
5
18
21
32
93
2
after sort:
2
5
9
18
21
32
93

 

插入排序

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4611360.html

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