编写函数,完成冒泡排序,要求不能改变下面的main函数。
//两个函数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函数
运行代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All gight reserved.
*文件名称:temp.cpp
*作者:邵帅
*完成时间:2014年11月20日
*版本号:v1.0
*/
#include<iostream>
using namespace std;
void bubble_sort(int s[],int n);
void output_array(int s[],int n);
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);
output_array(a,20);
bubble_sort(b,15);
output_array(b,15);
return 0;
}
void bubble_sort(int s[],int n)
{
int i,j,t;
for (j=1; j<=n-1; j++)
for (i=0; i<n-j; i++)
{
if (s[i]<s[i+1])
{
t=s[i];
s[i]=s[i+1];
s[i+1]=t;
}
}
}
void output_array(int s[],int n)
{
cout<<"降序后的数组是:";
for (int i=0; i<n; i++)
cout<<s[i]<<" ";
cout<<endl;
}
运行结果:
字符数组排序:改造程序,使其能对字符数组进行排序
int a[20]={...};
int b[15]={...};
改为:
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] = {'a','b','a',...};
运行代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All gight reserved.
*文件名称:temp.cpp
*作者:邵帅
*完成时间:2014年11月20日
*版本号:v1.0
*/
#include<iostream>
using namespace std;
//两个函数bubble_sort和output_array的声明
void bubble_sort(char s[],int n);
void output_array(char s[],int n);
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] = {'a','b','a','d','g','h','s','u','i','a','e','e','l','c','x'};
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;
char t;
for (j=1; j<=n-1; j++)
for (i=0; i<n-j; i++)
{
if (s[i]<s[i+1])
{
t=s[i];
s[i]=s[i+1];
s[i+1]=t;
}
}
}
void output_array(char s[],int n)
{
cout<<"降序后的数组是:";
for (int i=0; i<n; i++)
cout<<s[i]<<" ";
cout<<endl;
}
运行结果:
@ Mayuko