插入排序法(InsertSort)c++实现

来源:互联网 发布:儿童涂鸦画画软件 编辑:程序博客网 时间:2024/05/19 14:02

插入排序法就是把无序区的数据一个一个在有序区里找到自己的位置。
这就好比军训时,教官首先让最左边的人站着不动,然后从左边第二个人开始,如果他比第一个人高就不动,否则就排在第一个人的左边。接着看第三个人,把他与前两个人比,然后找到自己的位置,依次下去,直到最后一个人找到自己的位置。
c++实现:
InsetSort.h文件:
/**************************************************************/
class InsertSort
{
    const int arraySize;
    float *array;
public:
    InsertSort(int arraySize);
    ~InsertSort();
    void Initial();
    void Sort();
    void Show();
};
/***************************************************************/
InsertSort.cpp文件:
/***************************************************************/
#include <iostream>
#include "InsertSort.h"
using namespace std;

InsertSort::InsertSort(int size):arraySize(size)
{
}

void InsertSort::Initial()
{
    array= new float[arraySize];

    cout<<"please enter "<<arraySize<<" elements!"<<endl;

    for(int i=0;i<arraySize;i++)
    {
        cin>>array[i];
    }

    cout<<"entered!"<<endl;
}

void InsertSort::Sort()
{
    for(int j=1;j<arraySize;j++)
    {
        float temp=array[j];
        int i=j-1;
        while(temp<array[i])
        {
            array[i+1]=array[i];
            i--;
        }
        array[i+1]=temp;
    }
}

void InsertSort::Show()
{
    for(int i=0;i<arraySize;i++)
    {
        cout<<array[i]<<"  ";
    }
}

InsertSort::~InsertSort()
{
    delete [] array;
}
/**********************************************************/
main函数文件:
/*********************************************************/
#include <iostream>
#include "InsertSort.h"

using namespace std;

int main()
{
    cout<<"enter the size of array!"<<endl;
    int size;
    cin>>size;

    InsertSort test(size);

    test.Initial();
    test.Sort();
    test.Show();

    return 0;
}
/***********************************************************/

原创粉丝点击