我们在平时敲代码时,可以会遇到给某组值排序的情况。
下面这组代码,是简单给数组排序演示。
此代码为控制台显示程序:
#include <iostream>
//#include <atlstr.h>//如果需要用CString类时启用
#include<ctime>
using namespace std;
int main()
{
/*std::cout << "Hello World!\n";*/
srand((unsigned int)time(NULL));
int big[10];
for (int i = 0; i < 10; ++i)
{
big[i] = rand() % 500 + 100;
}
cout << "未排序前===================================================" << endl;
for (int b = 0; b < 10; ++b)
{
cout << "数字" << b + 1 << ":" << big[b] << "\t";
if (b == 4)
{
cout << endl;
}
}
cout << endl;
int tmp = 0;
bool bsort = true;//真为从小到到,假为从大到小
for (int w = 0; w < 10; ++w)
{
tmp = big[w];
for (int n = w + 1; n < 10; ++n)
{
if (bsort)
{
//从小到大排列
if (tmp > big[n])
{
tmp = big[n];
big[n] = big[w];
big[w] = tmp;
}
}
else
{
//从大到小排列
if (tmp < big[n])
{
tmp = big[n];
big[n] = big[w];
big[w] = tmp;
}
}
}
}
cout << "排序后===================================================" << endl;
for (int c = 0; c < 10; ++c)
{
cout << "数学" << c + 1 << ":" << big[c] << "\t";
if (c == 4)
{
cout << endl;
}
}
cout << endl;
system("pause");
}
演示的结果如图: