function FoamMethod(mat)
%冒泡法:将数组按从小到大的顺序进行排序
L=length(mat);
%newmat(L)=0;
button=questdlg('顺序还是倒序','排序','顺序','倒序','顺序');
switch button
%% 按从小到大的顺序进行排序
case '顺序'
for i=1:L-1
for j=1:L-i
if mat(j)>mat(j+1)
temp=mat(j);
mat(j)=mat(j+1);
mat(j+1)=temp;
end
end
end
disp(mat)
%% 按从大到小的顺序机械排序
case '倒序'
for i=1:L-1
for j=1:L-i
if mat(j)<mat(j+1)
temp=mat(j);
mat(j)=mat(j+1);
mat(j+1)=temp;
end
end
end
disp(mat)
end
end
上面代码是一个冒泡法函数,该函数可实现数组的顺序与倒序。而且可以自己选择是顺序还是倒序。