冒泡排序是最慢的排序算法。在实际运用中它是效率最低的算法。它通过一趟又一趟地比较数组中的每一个元素,使较大的数据下沉,较小的数据上升。它是O(n^2)的算法。
Soldiers
(Input File: input.txt)
There are N soldiers standing in a queue, in a general way, they align by their height, for instance, from shortest to tallest. But Coach Zhang is a strange drillmaster, and he would like to rearrange his soldiers’ positions so that the differences of height between every two adjacent soldiers are all distinct. Obviously, there are no two soldiers having the same height, because Coach Zhang carefully uses precision instruments to measure them.
Now your job is to write a program to help Coach Zhang to find such a rearrangement which can satisfy his need. You know there may be more than one solution, any of them is acceptable
Input:
The first line of input there is one integer T(T<=100), giving the number of test cases in the input. Each test case starts with a line containing a positive integer N(N<=10000), representing the number of the soldiers. In the next line there are N positive integers giving the height of these soldiers. Coach Zhang guaranteed that their height will be no more than 109. (a little incredible?).
Output:
For each test case, output one line with N integers in a queue, which represent a feasible solution.
Sample Input:
2
2
1 2
3
175 173 171
Sample Output:
1 2
171 175 173
#include<iostream>
#include<fstream>
#include<vector>
#include<cmath>
using namespace std;
int main()
{
//士兵队数、某队人数、身高
int soldierarray,numsoldier,soldierheight;
vector<int>v1; //身高
vector<int>v2; //身高sort
ifstream stream("input.txt");
stream>>soldierarray;
for(int i=1;i<=soldierarray;i++)
{
stream>>numsoldier;
//装载身高
for(int n=0;n<numsoldier;n++)
{
stream>>soldierheight;
v1.push_back(soldierheight);
}
v2.push_back(v1[0]);
v2.push_back(v1[1]);
for(int j=2;j<v1.size();j++)
{ vector<int>::iterator p=v2.begin();
int compare=v1[j];
int k=0;
for(k;k<v2.size()-1;k++)
{
if(k==0)
{
if(abs(compare-v2[k])!=abs(v2[k]-v2[k+1]))
{
v2.insert(p,compare);
break;
}
}
else
{
if((abs(compare-v2[k-1])!=abs(compare-v2[k]))
&&(abs(compare-v2[k])!=abs(v2[k]-v2[k+1])))
{
v2.insert(p+k,compare);
break;
}
}
}//for k
if(k>=(v2.size()-1))
{
if((abs(compare-v2[k-1])!=abs(compare-v2[k]))
&&abs((compare-v2[k-1])!=abs(v2[k-1]-v2[k-2])))
{
v2.insert((p+k,&compare));
}
else
{
if(abs(compare-v2[k])!=abs(v2[k]-v2[k-1]))
{
v2.push_back(compare);
}
else { return 0;}
}
}
}//for j
for(int k=0;k<v2.size();k++)
{
cout<<v2[k]<<" ";
}
cout<<endl;
v1.clear();
v2.clear();
}//for i
stream.close();
return 0;
}