计数排序
//以投票(洛谷P1271)为例
#include<iostream>
using namespace std;
int main()
{
int n = 0, m = 0,temp=0;
int a[9999]={0};
cin >> n >> m;//输入候选人(n)投票数(m)
for (int i = 0; i < m; ++i)
{
cin >> temp;
a[temp]++;
}
for (int i = 1; i <= n; ++i)
{
for (int j = 0; j < a[i]; ++j)
{
cout << i << " ";
}
}
cout << endl;
system("pause");
return 0;
}
选择排序
#include<iostream>
using namespace std;
int main()
{
int n = 0;
cin >> n;//输入数据数
int a[999]={0};//定义数组
for (int m = 0; m < n; ++m)//输入数据
{
cin >> a[m];
}
for (int i = 0; i < n-1; ++i)
{
for (int j =i+1; j < n; ++j)
{
if (a[j] < a[i])
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
for (int w = 0; w < n; ++w)//打印排列好的数据
{
cout << a[w]<<" ";
}
system("pause");
return 0;
}
冒泡排序
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;//输入数据数
int a[999] = { 0 };
for (int o = 0; o < n; ++o)//输入数据
{
cin >> a[o];
}
for (int i = 0; i < n-1; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if (a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (int w = 0; w < n; ++w)//打印排列好的数据
{
cout << a[w]<<" ";
}
system("pause");
return 0;
}