2009/11/10

[ C/C++ ] Insertion Sort by C++

Insertion sort is an elementary sorting algorithm. The time complexity of Θ(n2).

// insertSort.cpp
//
// Sorting Algorithm (insertion sort) .
//
// Console-based
// Retruns real as well as comples roots.
// Author Jim.lin 2009

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    unsigned int i, j, k, tmp;
    cout << "Please Input a Number :";
    cin >> k;
    vector<int> data(k); //定義一個整數型態k大小的向量陣列

    cout << "Please Input " << k << " Number :";
    for ( i=0; i < data.size(); ++i )
    cin >> data[i];

    // Begin Sorting
    for ( i=1; i < data.size(); ++i )
    {
        for (j=i; j>0; --j)
        {
            if (data[j] >= data[j-1] )
                break;
            else
            {
                tmp = data[j];
                data[j] = data[j-1];
                data[j-1] = tmp;
            }

        }
    }
    // Output Sorted
    cout << "\n Sorted Resulte:";
    for ( i=0; i<data.size(); ++i )
    cout << data[i] << " ";
    cout << endl;

    return 0;
}  

0 意見: