Chapter 2-InsertionSort

本文详细介绍了插入排序算法的基本思想和实现步骤,并提供了C++代码示例。通过实例演示了如何使用插入排序对不同数组进行排序。

Please indicate the source if you want to reprint: http://blog.youkuaiyun.com/gaoxiangnumber1.
插入排序(Insertion Sort)的基本思想是:每次将一个待排序的元素,按其大小插入到前面已经排好序的子序列中的适当位置,直到全部元素插入完成为止。
设数组为a[0…n-1]。
1.初始时,a[0]自成1个有序区,无序区为a[1..n-1]。令i=1。
2.将a[i]并入当前的有序区a[0…i-1]中形成a[0…i]的有序区间。
3.i++并重复第二步直到i==n-1。排序完成。

Time Complexity: O(n2)
Space Complexity: O(1)
InsertionSort.cc

#include<iostream>
using namespace std;

template<typename T>
void InsertionSort(T sort_array[], int length);

int main()
{
    int test_array1[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
    int test_array2[9] = {5, 0, -99, 3, 56, 7, 8, -55, 56};
    int test_array3[10] = {-1, -8, 50, 4, 20, 0, 45, 9999, 520, 555555};
    InsertionSort(test_array1, 10);
    InsertionSort(test_array2, 9);
    InsertionSort(test_array3, 10);
    cout << "test_array1:\n";
    for(int index = 0; index < 10; index++)
    {
        cout << test_array1[index] << " ";
    }
    cout << "\ntest_array2:\n";
    for(int index = 0; index < 9; index++)
    {
        cout << test_array2[index] << " ";
    }
    cout << "\ntest_array3:\n";
    for(int index = 0; index < 10; index++)
    {
        cout << test_array3[index] << " ";
    }
    cout << endl;

    return 0;
}

template<typename T>
void InsertionSort(T sort_array[], int length)
{
    // sort_index is the index of element that we want to insert now
    // sort_array[0] is automatically sorted, so sort_index begins from 1
    for(int sort_index = 1; sort_index < length; sort_index++)
    {
        // store element in key
        T key = sort_array[sort_index];
        // compare from end to front only use 1 loop: move elements and
        // find proper position to insert key concurrently. Because when we can't move
        // elements, we find the proper position.
        // Otherwise compare from front to end use 2 loops: find the proper position
        // in one loop; and move elements in the other loop.
        int compare_index = sort_index - 1;  // compare from end to front
        while(compare_index >= 0 && sort_array[compare_index] > key)
        // if key is smaller than some elements in the front-sorted-array, then move
        {
            // we assume sort_array[compare_index + 1] = key before moving
            sort_array[compare_index + 1] = sort_array[compare_index];
            compare_index--;  // continue
        }
        // when we can't move elements, we find the proper position to insert key.
        sort_array[compare_index + 1] = key;
    }
}

Please indicate the source if you want to reprint: http://blog.youkuaiyun.com/gaoxiangnumber1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值