Sorting is a very important concept in computer science. The basic idea is that
ID: 3915621 • Letter: S
Question
Sorting is a very important concept in computer science. The basic idea is that an unsorted list of numbers is assigned to a vector. The numbers are then ordered by a process which essentially passes through the vector many times, swapping consecutive elements that are in the wrong order, until all elements are in the right order 1. 2. 3. Generate a random vector X of numbers of length N Set N to the length of X Repeat N-1 times with the counter K a. Repeat N-K times with counter J b. IfXj> Xj+1 thern i. Swap the contents of Xj and Xj+1 4. Stop since the list is sorted Submit your program in a well-document MATLAB script bubbleSort.m. Here the program should NOT use MATLAB's vectorizing commands Make sure your program works for N-5 first. Print out the vector (during program debugging) each time through the sort. Suppress the vector display when timing (profiling) your code below Hints: After the program is working, determine the time it takes to sort 200 random numbers using the built in commands tic and toc. Compare it to the time it takes MATLAB to perform the sort using the sort command. Why is there a discrepancy? 2Sort the N - 5 element column vector 2 11 1 22 9 3 33 3 3 92 22 2 2 9 11 1 1 1 9 5 5 5 559 3 2 2 2 2 3 1 1 11 3 3Explanation / Answer
function x = bubblesort(x)
%--------------------------------------------------------------------------
% Syntax: sx = bubblesort(x);
%
% Inputs: x is a vector of length n
%
% Outputs: sx is the sorted (ascending) version of x
%
% Description: This function sorts the input array x in ascending order
% using the bubble sort algorithm
%
% Complexity: O(n) best-case performance
% O(n^2) average-case performance
% O(n^2) worst-case performance
% O(1) auxiliary space
%--------------------------------------------------------------------------
% Bubble sort
n = length(x);
while (n > 0)
% Iterate through x
nnew = 0;
for i = 2:n
% Swap elements in wrong order
if (x(i) < x(i - 1))
x = swap(x,i,i - 1);
nnew = i;
end
end
disp(x)
n = nnew;
end
end
function x = swap(x,i,j)
% Swap x(i) and x(j)
% Note: In practice, x xhould be passed by reference
val = x(i);
x(i) = x(j);
x(j) = val;
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.