- #1

- 11

- 0

## Main Question or Discussion Point

This is what I had originally

function out = msort(x)

%This function helps sort numbers in ascending and descending order.

%To put in descending order, user must include 'd' in the input.

y = length(x);

sorted = 0;

n = 0;

while ~sorted

sorted = 1;

for i = 1:y-1

if x(i) > x(i+1)

n = n + 1;

t = x(i);

x(i) = x(i+1);

x(i+1) = t;

sorted = 0;

end

end

end

% while ~sorted

% sorted = 1;

% for i = 1:y-1

% if x(i) < x(i+1)

% n = n + 1

% t = x(i);

% x(i) = x(i+1);

% x(i+1) = t;

% sorted = 0;

% end

% end

% end;

out = x;

The program works if i set x = to a set of numbers and run msort(x), it won't work if I do msort(10,9,5,4). It will work if I do msort([10,9,5,4]). I realized I have to use varargout and varargin which leads me to change the first line of the program to:

function [varargout] = msort(varargin)

but if I change that I am not sure how I would change the rest of the code with all the x's, and I'm also not sure how I would be able to show the number of swaps with the sorted numbers like

[b,n] = msort(10,9,5,4)

b = 4,5,9,10

n = 6 (number of swaps)

I didn't do the descending part of the program yet. Please help! Thanks

function out = msort(x)

%This function helps sort numbers in ascending and descending order.

%To put in descending order, user must include 'd' in the input.

y = length(x);

sorted = 0;

n = 0;

while ~sorted

sorted = 1;

for i = 1:y-1

if x(i) > x(i+1)

n = n + 1;

t = x(i);

x(i) = x(i+1);

x(i+1) = t;

sorted = 0;

end

end

end

% while ~sorted

% sorted = 1;

% for i = 1:y-1

% if x(i) < x(i+1)

% n = n + 1

% t = x(i);

% x(i) = x(i+1);

% x(i+1) = t;

% sorted = 0;

% end

% end

% end;

out = x;

The program works if i set x = to a set of numbers and run msort(x), it won't work if I do msort(10,9,5,4). It will work if I do msort([10,9,5,4]). I realized I have to use varargout and varargin which leads me to change the first line of the program to:

function [varargout] = msort(varargin)

but if I change that I am not sure how I would change the rest of the code with all the x's, and I'm also not sure how I would be able to show the number of swaps with the sorted numbers like

[b,n] = msort(10,9,5,4)

b = 4,5,9,10

n = 6 (number of swaps)

I didn't do the descending part of the program yet. Please help! Thanks