PROGRAMMING IN MATLAB Write a function with the header: function [x] = myBubbleS
ID: 3674205 • Letter: P
Question
PROGRAMMING IN MATLAB
Write a function with the header: function [x] = myBubbleSort(x),
which sorts a one-dimensional vector x using a bubble sort algorithm. In the output vector, x(1) should contain the smallest value and x(n) should be the largest value. The bubble sort compares pairs of elements. If the element on the left is greater than the element on the right, they are swapped: the j th element of x is compared to the j+1th element of x. If the element on the left, x(j), is greater than the element on the right, x(j+1), the two elements are swapped. If this is swapping is done inside nested for-loops, then the entire vector will sorted at the end.
Outer loop, i: Cycles from one to length of x - 1
Inner loop, j: Cycles from one to length of x - i
NOTE: You must use nested for loops. You may not use Matlab built-in sorting functions.
Explanation / Answer
BUBBLE SORT
-----------------------------------------------------
% The vector of numbers are
disp (‘INPUTS’)
disp(‘Input the vector of numbers’)
A=[18 7 6 15 4 13];
disp(A)
% Number of entries, n
n=length(A);
% making (n-1) passes
for j=1:1:n-1
% comparing each number with the next and swapping
for i=1:1:n-1
if A(i)>A(i+1);
% temp is a variable where the numbers are kept
% temporarily for the switch
temp=A(i);
A(i)=A(i+1);
A(i+1)=temp;
end
end
end
%% DISPLAY OUTPUT
disp(‘ ‘)
disp (‘-------------OUTPUT---------------------’)
disp (‘The ascending matrix is’)
disp(A)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.