题目描述
请创建一个一维整型数组用来存储待排序关键码,关键码从数组下标为1的位置开始存储,下标为0的位置不存储关键码。输入关键码的个数,以及各个关键码,采用起泡排序的方法对关键码数组进行排序,输出每轮比较的过程。
输入描述
各个命令以及相关数据的输入格式如下:
第一行输入关键码的个数n
第二行输入n个整型关键码
输出描述
输出关键码比较过程,即输出交换的两个关键码中后面一个,每轮一行,关键码之间以空格隔开,最后一个关键码后有空格,然后回车,不重复输出。
最后输出排好序的关键码,以空格隔开,最后回车。
输入样例
10
2 5 9 8 7 4 3 10 16 13
输出样例
8 7 4 3 13
7 4 3
4 3
4 3
3
2 3 4 5 7 8 9 10 13 16
#include<iostream>
#define MAXSIZE 100
using namespace std;
void BubbleSort(int a[],int l)
{
int j, exchange, bound, temp;
int length=l;
int data[length];
for(int k=0;k<=length;k++) //进行赋值
{
data[k]=a[k];
}
exchange = length - 1; //第一趟起泡排序的区间是[0~length-1]
while (exchange != 0)
{
bound = exchange; exchange = 0;
for (j = 0; j < bound; j++) //一趟起泡排序的区间是[0~bound]
{
if (data[j] > data[j+1])
{
temp = data[j]; data[j] = data[j+1]; data[j+1] = temp;
exchange = j; //记载每一次记录交换的位置
cout<<data[j]<<' '; //交换后j存了那个较小的
}
//cout<<endl;
}
}
for(int p=1;p<length;p++)
{
cout<<data[p]<<' ';
}
}
int main()
{
int n;
cin>>n;
int a[n+1];
a[0]=0; //设置哨兵
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
BubbleSort(a,n+1);
return 0;
}
欢批评指正:)