matlab代码冒泡排序
时间: 2023-10-12 13:09:55 浏览: 34
Sure, I can help you with that. Here's a sample code for bubble sort in MATLAB:
```MATLAB
function sorted_array = bubbleSort(array)
% Bubble sort algorithm in MATLAB
% Input: array -- the unsorted array
% Output: sorted_array -- the sorted array
n = length(array);
while true
swapped = false;
for i = 1:n-1
if array(i) > array(i+1)
% swap the elements
temp = array(i+1);
array(i+1) = array(i);
array(i) = temp;
swapped = true;
end
end
if ~swapped
% no swap occurred in previous pass, array is sorted
break;
end
end
sorted_array = array;
end
```
To use the above function, you can call it as follows:
```MATLAB
unsorted_array = [7, 3, 5, 1, 4];
sorted_array = bubbleSort(unsorted_array);
disp(sorted_array);
```
This will output the sorted array: 1 3 4 5 7.
I hope this helps! Let me know if you have any other questions.