Write a function with the header: function [x] = myBubbleSort(x) whichsortsaone-
ID: 3672069 • Letter: W
Question
Write a function with the header:
function [x] = myBubbleSort(x)
whichsortsaone-dimensionalvectorxusingabubblesortalgorithm. 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 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
Explanation / Answer
def myBubbleSort(x):
n = len(x)
for i in range(0, n):
for j in range(0, n - i - 1):
if (x[j + 1] < x[j]):
tmp = x[j]
x[j] = x[j + 1]
x[j + 1] = tmp
return x
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.