问题 问答题

请编写一个函数void fun(int a [],int n),其中a为数组,n为数组a的长度。函数fun()的功能是冒泡排序法将数组a元素按从小到大的顺序排列,实现数组a的升序排列。 注意:部分源程序已存在文件PROC12.cpp中。 请勿修改主函数和其他函数中的任何内容,仅在函数fun()的花括号中填写若干语句。 文件PROC12.cpp的内容如下: //PROC12. cpp #include <iostream> using namespace std; #define MAX 100 void fun(int a[],int n); int main () { int a[MAX],n,i; cout<<"Please enter the array size n:\n"; do { cin>>n; if (n>100) cout<<"array size flowover! ReEnter a number(0-100)\n"; }while (n>100); cout<<"Enter the array data:\n"; for (i=0; i<n; i++) cin>>a [ii; fun(a[],n); for (i=0; i<n; i++) cout<<a [i] <<" "; cout<<end1; return 0; } void fun(int a[ ],int n) { // * * * * * * * * }

答案

参考答案:

解析:函数fun()的定义如下: void fun(int a[ ],int n) { int F=n; while(F>0) { int k=F-1; F=0; for(int j=1;j<=k;j++) { if(a[j]>a[j+1]) { int temp=a[i]; a[j]=a[i+1]; a[j+1]=temp; F=j; } } } return; } 将待排序的数存放于数组a中,首先比较a[1]和a[2],如果9[1]>a[2],则交换这两个元素的值,接着比较a[2]和a[3],此时的a[2]可能是刚交换来的值,若a12)>a[3],则交换这两个元素的值,依此类推,直到处理完a[n-1)和a[n]这两个元素的比较。经过了n-1次的比较处理,最大的数被传到数组最后一个元素中,而较小的数就会像气泡一样上浮。 在上述算法的实现函数中,k表示每遍扫描时需要进行比较的项目数。当F>0时,表示在上遍扫描过程中曾经发生过交换,还需要进行扫描。F的数值表示上一遍扫描过程中最后一次发生交换的位置。

单项选择题 A1/A2型题
多项选择题