// 7_a1.cpp -- 插入排序练习
/**
* -> 题目要求:
* 1. 编写一个插入排序的算法,并且在main函数中验证其功能已实现。
* 2. 此题的源程序保存为 7_a1.cpp。
**/
/**
* -> 题目分析流程:
* 1. 在main函数中输入N个数值。
* 2. 显示排序前的这N个数值。
* 2. 调入插入函数的子程序。
* 3. 显示调用后的排序结果。
**/
/**
* -> 主要算法分析:
* 见01_sortproblem.cpp(此处不重复了)
**/
#include <iostream>
#include <vector>
#include <conio.h> // _getch();
using std::cin; // using 声明
using std::cout;
using std::endl;
using std::vector;
// ________________________ 主函数 _______________________________
int main()
{
void InsertArr(vector<double> & test);
void InsertSort(vector<double> & test);
void ShowArr(vector <double> & test);
bool testagain(true);
char testagainjudge;
vector<double> testArr; // 用于测试的数组
do
{
cout << "------------------------- 现在开始数组的插入排序测试 ---------------------------\n";
cout << " -> 说明:该测试共分为三个步骤:输入 -> (系统内部)排序 -> 输出显示.\n"
<< "-> 注意:在输入时,请按任意字母结束输入。\n";
// 插入
InsertArr(testArr);
ShowArr(testArr);
cout << endl;
// 排序
InsertSort(testArr);
ShowArr(testArr);
cout << endl;
cout << "-> 如需重新测试,请按字符'a',否则请按任意键退出...";
testagainjudge = _getch();
if (testagainjudge == 'a')
{
cin.sync();
testArr.clear();
testagain = true;
system("cls");
}
else
{
testagain = false;
}
}while (testagain);
return 0;
}
/**
* 子程序名称:InsertArr
* 子程序返回类型:void
* 子程序入口参数:vector<double> &
* 子程序功能:由用户设定N个数值,并由用户输入这N个数值,程序将其保存入vector<double>入口参数处。
**/
void InsertArr(vector<double> & test)
{
cout << "-> 请输入需要输入的数值个数:";
unsigned int n;
cin >> n;
cout << "-> 现在开始数值输入(请以空格间开):";
for ( unsigned int i = 0; i < n; ++i)
{
double value;
cin >> value;
while(cin.fail())
{
cin.sync();
cin.clear();
cin >> value;
}
test.push_back(value);
}
cout << "-> 输入操作完成.\n";
return;
}
/**
* 子程序名称:InsertSort
* 子程序返回类型:void
* 子程序入口参数:vector<double> &
* 子程序功能:将vector<double>内部从小到大的顺序排序。
**/
void InsertSort(vector<double> & test)
{
int n = static_cast<int>(test.size());
int i(1);
int j(0);
for (i; i < n; ++i)
{
vector<double>::value_type temp = test[i];
for (j = i -1; j >= 0 && temp < test[j]; j--)
{
test[j + 1] = test[j];
}
test[j+1] = temp;
}
return;
}
/**
* 子程序名称:ShowArr
* 子程序返回类型:void
* 子程序入口参数:vector<double> &
* 子程序功能:遍历并显示vector<double>&。
**/
void ShowArr(vector <double> & test)
{
cout << "-> 现在开始显示确认刚刚所输入的数组顺序:\n";
cout << "-> ";
vector<double>::const_iterator be(test.begin());
vector<double>::const_iterator en(test.end());
while ( be != en)
{
cout << *be++ << " ";
}
return;
}