冒泡排序
练习
Second text Hao Long
代码片
.
#include<iostream>
using namespace std;
int main()
{
int n,t;
int i,j;
int a[999]; //定义数组[]中必须是整数,或者define定义的字符常量,不确定需要排序多少个数字所以定义一个较大的数
cout << "Please enter the number of Numbers to be entered:" << endl;
cin >> n; //请输入将要输入数字的个数
cout << "Please enter array:" << endl;
for(i=0;i<n;i++){
//这是方便输入时理解的
cout << "a[" << i << "]:"; //可以注释掉
cin >> a[i]; //循环输入值给数组
}
for(i=0;i<n;i++){
cout << a[i] << " "; //输出一遍看看
}
cout << endl;
for(i=0;i<n;i++){ //这是用来帮助减少计算的
for(j=0;j<n-1-i;j++){ //主要,每次外循环(就是i++的一次)都从a[0]开始比较到a[n-1-i]结束,一共比较n次 //这里用n-1-i要不然就越界了(就是第一次循环,i=0的时候,j<n-i,j最大是n-1,此时j+1=n,a[j+1]是不存在的,)
if(a[j]<a[j+1]){ //比较大小如果后一项大就交换值,这个"<"决定排序是从大到小的,若想换成从小到大可以改成">"
t=a[j]; //这里有一个中间变量t,用来暂存a[j]的值,用于交换
a[j]=a[j+1];
a[j+1]=t;
}
}
}
cout << "The bubble sorted result is:" << endl;
for(i=0;i<n;i++){ //输出冒泡排序后的数组
cout << a[i] << " ";
}
return 0;
}
学生按成绩排序
#include<iostream>
using namespace std;
struct student {
char name[21];
int score;
}; //创建一个结构体,用来存储姓名和分数
typedef student Student;
int main()
{
Student a[124],t;
int num;
cout << "the number of students: ";
cin >> num;
for (int i = 0; i < num; i++) {
cout << "name: ";
cin >> a[i].name;
cout << "score: ";
cin >> a[i].score;
}
for (int i = 0; i < num - 1; i++) { //排n - 1遍,最后一遍不用排
for (int j = 0; j < num - i - 1; j++) { //从第一位开始比较直到最后一个尚未归位的数,需要- 1不然会越界(比较时有a[j+1])
if (a[j].score < a[j+1].score) {
t = a[j]; //换的是结构体(包括姓名和分数)
a[j] = a[j+1];
a[j+1] = t;
}
}
}
for(int i = 0; i < num; i++) {
cout << a[i].name << " ";
}
getchar();
getchar(); //用来暂停程序,以便查看程序输出的内容,可用system("pause");等来代替
return 0;
}
Run:
快速排序
#include<iostream>
using namespace std;
int a[124],n; //全局变量
void quicksort (int left,int right) {
int i,j,t,temp;
if(left > right) {
/*cout << "error: left: " << left << " right: " << right << endl;
for(int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;*/ //测试输出时所用
return ;
}
temp = a[left]; //temp中存的就是基准数(和此数比较大小)
i = left;
j = right;
while(i != j) {
//顺序很重要,一定要先从右往左找(比基准数小的)
while(a[j] >= temp && j > i) j--;
while(a[i] <= temp && i < j) i++;
if(i < j) { //哨兵1和哨兵2还没相遇时
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];
a[i] = temp; //基准数归位
/*cout << "testoutput: left: " << left << " right: " << right << endl;
for(int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;*/ //测试输出时所用
quicksort(left,i - 1);
quicksort(i + 1,right); //调用函数,分别排左右,这是一个递归过程
}
int main()
{
cout << "input n: ";
cin >> n;
cout << "input number: " << endl;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
quicksort(0,n - 1);
for(int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
getchar();
getchar();
return 0;
}
Run:
计算机的无脑与强大之处:(不管是否已经是最终结果,都会执行到底)