Write a function that returns the values of the two inputs in reversed order: fu
ID: 2083081 • Letter: W
Question
Write a function that returns the values of the two inputs in reversed order: function [a, b] = swap(x, y). To use it to swap the values of two variables simply write [v1, v2] = swap(v1, v2). A respectable sorting method is the bubble sort. Examine in turn each element of the vector and it's neighbor to the right. If they're in the wrong order, swap them. Continue going repeatedly through the vector in this way until the whole vector has been traversed once with no swaps. a. Write a function vout = bubble Sort(v) that sorts a vector by this method.Explanation / Answer
Swap.
Initially create the function file swap.m
Enter the following code:
function [v1,v2] = swap(v1,v2)
syms a;
a=v1; % temp variable to store data
v1=v2;
v2=a;
Save this file.
Now, Create a new file and write the following code.
% swap
clc;
clear all;
fprintf('Enter the 2 numbers=');
v1=input('');
v2=input('');
[v1,v2]=swap(v1,v2)
Run this file. You will be prompted to enter 2 numbers. These number will then be swapped.
Bubble Sort.
Initially create the function file bubbleSort.m
Enter the following code:
function vout=bubbleSort(v,n)
for j=1:1:(n-1)
for i=1:1:(n-1) % start from 1. Increment by 1, till (n-1)
if v(i)>v(i+1)
a=v(i);
v(i)=v(i+1);
v(i+1)=a;
end
end
end
vout=v;
Save this file.
Now, Create a new file and write the following code.
clc;
clear all;
fprintf('Enter the array of numbers=');
v=input('')
n=length(v); % calculates the no. of elemenths in vector v
fprintf('The input vector after sorting is ');
vout=bubbleSort(v,n)
Run this file. You will be prompted to enter the array. Enter the elements of array in [ ] brackets.
e.g. Enter the array of numbers=[2 4 1 5 3]
Output Result:
The input vector after sorting is
vout =
1 2 3 4 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.