桶排序
#include <iostream>
using namespace std;
int main () {
int book[1001]; // 下标是0-1000
int temp; //用来临时存放读取的数
for (int i = 0; i <= 1001; i++)
{
book[i] = 0; //完成初始化
}
int num; //设定有几个数进行比较
cin >> num;
for (int i = 1; i <= num; i++)
{
cin >> temp;
book[temp] ++ ;
} //进行桶排序
for (int i = 1000; i >= 0; i--)
{
for (int j = 1; j <= book[i]; j++)
{
cout << i <<" ";
}
} //1000到0 每个桶看一遍,桶里有几个球就打印这个桶标号几次
system("pause");
}
冒泡排序
#include <iostream>
using namespace std;
int main () {
int a[100];
int num;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> a[i];
}
/*以下为冒泡排序
*/
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num - i; j++)
{
if (a[j] < a[j+ 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
//循环输出
for (int i = 0; i < num; i++)
{
cout << a[i] << " ";
}
system("pause");
}
改进:对学生信息进行排序,根据成绩高低排序,输出成绩与姓名
#include <iostream>
using namespace std;
struct student
{
char name[21];
int score;
};
int main () {
struct student a[100];
int n; cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i].name >> a[i].score;
}
//排序,按照成绩高低
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
if (a[j].score < a[j + 1].score)
{
struct student temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
//输出成绩高低及 名字
cout << "成绩高低及分数为: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i].name << ' ' << a[i].score << endl;
}
system("pause");
}
快速排序
#include <iostream>
using namespace std;
int a[100];//存放数据
int n; //表示有几个数
void quicksort (int left , int right) {
int temp = a[left];//就是存基数的
int i = left;
int j = right;
if (left > right)
{
return;
}
while (i != j)
{
//顺序很重要,得先从右往左找
while (a[j] >= temp && i < j) j --;
while (a[i] <= temp && i < j ) i ++;
if (true)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
//然后将基数归位,就是最左边的数
a[left] = a[i]; //就是最左边的那个基准数跟在 中间它本该在的位子上那个数交换
a[i] = temp; //temp一直存放着基准数,就是最左边的数
//然后进行递归
quicksort(left, i -1);
quicksort(i + 1, right);
return ;
}
int main () {
cout << "输入要排序的数的个数" << endl;
cin >> n;
cout << "输入每个数" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
quicksort(0, n-1);
cout << "排完序后为: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << " " ;
}
system("pause");
}