编函数,完成冒泡排序。要求不能改变下面的main函数。
重点体会:(1)排序算法;(2)数组名作形式参数,将能改变作为实际参数的数组的值,实际参数传递给形式参数的是数组的地址值,也是传值;(3)形式参数中不指定数组大小,实际数组的大小也一并作为参数传递。
#include <iostream>
using namespace std;
void bubble_sort(int s[],int n);
void output_array(int s[],int n);
//两个函数bubble_sort和output_array的声明
int main( )
{
int a[20]= {86,76,62,58,77,85,92,80,96,88,77,67,80,68,88,87,64,59,61,76};
int b[15]= {27,61,49,88,4,20,28,31,42,62,64,14,88,27,73};
bubble_sort(a,20); //用冒泡法按降序排序a中元素
output_array(a,20); //输出排序后的数组
bubble_sort(b,15); //用冒泡法按降序排序b中元素
output_array(b,15); //输出排序后的数组
return 0;
}
//请在下面定义bubble_sort和output_array函数
void bubble_sort(int s[],int n)
{
int i,j,d=0;
for(j=0; j<n-1; j++)//共进行n-1趟比较
for(i=0; i<n-1-j; i++)//在每趟中要进行n-j次两两比较
{
if(s[i]<s[i+1])
{
d=s[i];
s[i]=s[i+1];
s[i+1]=d;
}
}
cout<<endl;
return;
}
void output_array(int s[],int n)
{
int i;
for(i=0; i<n-1; i++)
{
cout<<s[i]<<" ";
}
cout<<s[n-1]<<"\n";
return;
}
字符数组排序
修改程序,对字符数组进行排序。
#include <iostream>
using namespace std;
void bubble_sort(char s[],int n);
void output_array(char s[],int n);
//两个函数bubble_sort和output_array的声明
int main( )
{
char a[20]= {'s','o','r','t','b','u','b','b','l','e','s','e','l','e','c','t','o','k','o','k'};
char b[15]= {'s','o','r','t','b','u','b','b','l','e','s','e','l','e','c'};
bubble_sort(a,20); //用冒泡法按降序排序a中元素
output_array(a,20); //输出排序后的数组
bubble_sort(b,15); //用冒泡法按降序排序b中元素
output_array(b,15); //输出排序后的数组
return 0;
}
//请在下面定义bubble_sort和output_array函数
void bubble_sort(char s[],int n)
{
int i,j,d=0;
for(j=0; j<n-1; j++)//共进行n-1趟比较
for(i=0; i<n-1-j; i++)//在每趟中要进行n-j次两两比较
{
if(s[i]<s[i+1])
{
d=s[i];
s[i]=s[i+1];
s[i+1]=d;
}
}
cout<<endl;
return;
}
void output_array(char s[],int n)
{
int i;
for(i=0; i<n-1; i++)
{
cout<<s[i]<<" ";
}
cout<<s[n-1]<<"\n";
return;
}
365

被折叠的 条评论
为什么被折叠?



