您的位置:首页 > 编程语言 > C语言/C++

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

2010-06-03 20:05 549 查看
插入排序法就是把无序区的数据一个一个在有序区里找到自己的位置。
这就好比军训时,教官首先让最左边的人站着不动,然后从左边第二个人开始,如果他比第一个人高就不动,否则就排在第一个人的左边。接着看第三个人,把他与前两个人比,然后找到自己的位置,依次下去,直到最后一个人找到自己的位置。
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;
}
/***********************************************************/

转载:http://blog.csdn.net/justmeh/archive/2009/10/27/4734162.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: