本文轉載自頭條文章原文章地址
1、bubble_sort.m
function y=bubble_sort(x)
x_len=length(x);
for i=1:x_len-1
for j=1:x_len-i
if(x(j)>x(j+1))
[x(j),x(j+1)]=swap(x(j),x(j+1));
end
end
disp([num2str(i),'.Sort:x=',num2str(x)]);
end
y=x;
end
function [a,b]=swap(x,y)
a=y;
b=x;
end
2、test.m
clc;
clear;
X=randperm(9);
disp(['Before Sort:X=',num2str(X)]);
disp('--------------------');
y=bubble_sort2(X);
disp(['Bubble Sort:x=',num2str(y)]);
3、bubble_sort2.m (optimal)
function y=bubble_sort2(x)
x_len=length(x);
flag=1;%flag爲0,這說明已經排好序,不用繼續循環
for i=1:x_len-1
if flag
flag=0;
for j=1:x_len-i
if(x(j)>x(j+1))
[x(j),x(j+1)]=swap(x(j),x(j+1));
flag=1;%有交換 則說明還需要循環
end
end
disp([num2str(i),'.Sort:x=',num2str(x)]);
end
end
y=x;
end
function [a,b]=swap(x,y)
a=y;
b=x;
end