八大排序之插入排序

#include <iostream>

using namespace std;

template <class T>
void InsertSort(T* numbers, const int length);

int main()
{
    int length = 0;
    while (cin >> length)
    {
        int* pData = new int[length];
        for (int i = 0; i < length; ++i)
            cin >> pData[i];

        InsertSort(pData, length);

        for (int i = 0; i < length; ++i)
            cout << pData[i] << " ";

        cout << endl;

        delete[]pData;
        pData = NULL;
    }

    system("pause");
    return 0;
}

template <class T>
void InsertSort(T* numbers, const int length)
{
    if (numbers == NULL || length <= 0)
    {
        cout << "Error: invalid parameters!" << endl;
        return;
    }

    int leftIndex = 0, rightIndex = 0;
    T temp = 0;
    for (rightIndex = 1; rightIndex < length; ++rightIndex)
    {
        temp = numbers[rightIndex];
        leftIndex = rightIndex - 1;
        while (leftIndex >= 0 && numbers[leftIndex] > temp)
        {
            numbers[leftIndex + 1] = numbers[leftIndex];
            --leftIndex;
        }
        numbers[leftIndex + 1] = temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章