Which sorts a one-dimensional vector x using a bubble sort algorithm. In the out
ID: 3672080 • Letter: W
Question
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 jth 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 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 - iExplanation / Answer
function [x] = myBubbleSort(x)
len = size(x,1);
% Outer loop
for i = 1:len-1
% Inner loop
for j = 1:len-1
% Swapping Values if unsorted condition is found
if (x(:,j) > x(:,j+1))
res = x(:,j);
x(:,j) = x(:,j+1);
x(:,j+1) = res;
end
end
end
end
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.