问题

软件 >> MatLab
Questions in category: MatLab (MatLab).

[MATLAB]用起泡法(冒泡法)对10个数由小到大进行排序

Posted by haifeng on 2019-06-29 09:06:25 last update 2019-06-29 16:10:46 | Answers (1) | 收藏


[Exer P.30, 1]《数学建模与数学实验》

用起泡法(冒泡法)对10个数由小到大进行排序, 即将相邻两个数进行比较, 小的放到大的前面.


Remark: 当然冒泡法排序不是好的排序算法, 其算法复杂度为 $O(N^2)$.

 

下面是学生写的代码, 请改进

function f=qipaofa(x)
for j=9:-1:1
          for i=1:j
             if(x(i)>x(i+1))
                t=x(i);x(i)=x(i+1);x(i+1)=t;
             end
          end
end
f=x;

% for test
% x=round(10*rand(1,10));


学生2使用C语言编程, 请改进

#include<stdio.h>
main()
{int a[10],i,j,t;
printf("请输入10个数:");
for(i=0;i<10;i++)
scanf("%d",&a[i]);

for(j=0;j<9;j++)
   for(i=0;i<9-j;i++)
            if(a[i]>a[i+1])
            {t=a[i];a[i]=a[i+1];a[i+1]=t;}

            for(i=0;i<10;i++)
                      printf("%3d",a[i]);

            printf("\n");

}