先看这道题目的输入和输出
输入:
0
21 25 49 25 16 8
输出:
21 25 49 25 16 8
21 25 49 25 16 8
21 25 25 49 16 8
16 21 25 25 49 8
8 16 21 25 25 49
排序过程如下
首先先设置一个变量t,指向数列第二个位置。
每次都从1到t-1进行遍历,如果A[t]比A[j]小可以插入j前部,就插入,否则不操作。
所以,就可以轻松写出代码(如下)。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
template<class ElemType>
void SimpleInsertSort(vector<ElemType>& A)
{
int i, j, k;
int t;
t = 1;
if (A.size() == 0)
return;
if (A.size() == 1)
{
cout << A[0] << endl;
return;
}
for (i = 0;i < A.size()-1; i++)
{
for (j = 0; j < t; j++)
{
if (A[t] <= A[j])
break;
}
int temporary_p = j;
ElemType temporary_num = A[t];
for(j=t;j> temporary_p;j--)
A[j] = A[j-1];
A[temporary_p] = temporary_num;
t++;
for (k = 0; k < A.size(); k++)
cout << A[k] << " ";
cout << endl;
}
}
int main()
{
vector<int> input_int;
vector<double> input_double;
vector<char> input_char;
vector<string> input_string;
int kinds_num;
cin >> kinds_num;
if (kinds_num != 0 && kinds_num != 1 && kinds_num != 2 && kinds_num != 3)
{
cout << "err" << endl;
return 0;
}
if (kinds_num == 0)
{
int temporary_int;
while(cin>> temporary_int)
input_int.push_back(temporary_int);
}
if (kinds_num == 1)
{
double temporary_double;
while (cin >> temporary_double)
input_double.push_back(temporary_double);
}
if (kinds_num == 2)
{
char temporary_char;
while (cin >> temporary_char)
input_char.push_back(temporary_char);
}
if (kinds_num == 3)
{
string temporary_string;
while (cin >> temporary_string)
input_string.push_back(temporary_string);
}
if (kinds_num == 0)
{
SimpleInsertSort(input_int);
}
if (kinds_num == 1)
{
SimpleInsertSort(input_double);
}
if (kinds_num == 2)
{
SimpleInsertSort(input_char);
}
if (kinds_num == 3)
{
SimpleInsertSort(input_string);
}
return 0;
}