Help on selection sort function

8 views (last 30 days)
Maroulator
Maroulator on 12 Oct 2014
Commented: Maroulator on 13 Oct 2014
I have put together the ssort function below that takes in two arguments; one array that gets sorted and an argument ('up', 'down') that tells the function to sort in ascending('up') or descending('down') order. For example ssort([5 7 2 12 6],'up') sorts the array in the argument in ascending order.
I am trying to make it so that even if the second argument is never entered, the input array will default to being sorted in ascending order. Unfortunately in my code below, I have only managed to default to sorting for ascending order for ssort([5 7 2 12 6], ' ') which is not the same as running ssort([5 7 2 12 6]) which is what I am looking to accomplish. When I attempt to run ssort([5 7 2 12 6]), I get an error telling me that I have too few input arguments. Any insight would be extremely appreciated.
function out = ssort(a,b)
%SSORT Selection sort data; data may be sorted in ascending or descending order
%Function SSORT sorts a numeric dataset into desired order.
narginchk(1,2);
nvals=size(a,2);
if nvals==0 || nvals==1
msg='You have not entered a proper array for sorting';
error(msg);
end
for ii=1:nvals-1
iptr=ii;
for jj=ii+1:nvals
if strcmp(b,'up')==1
if a(jj)>a(iptr)
iptr=jj;
end
elseif strcmp(b,'down')==1 || isempty(b)==1
if a(jj)<a(iptr)
iptr=jj;
end
else
k='Invalid sorting option!';
error(k);
end
end
if ii~=iptr
temp = a(ii);
a(ii) = a(iptr);
a(iptr) = temp;
end
end
out=a;
  2 Comments
the cyclist
the cyclist on 13 Oct 2014
Is there a reason you are not just using the built-in sort function, as provided by MATLAB? Is this a homework assignment to write your own sort?
Maroulator
Maroulator on 13 Oct 2014
Correct; this is a homework assignment that requires me to write my own sort function.

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 13 Oct 2014
Trying putting these lines just after you check the number of arguments:
if nargin < 2
b = 'up'
end
Also, 'up' seems to sort in what is normally called descending order (from highest value down to lowest). Is that what you intended?

More Answers (1)

Image Analyst
Image Analyst on 13 Oct 2014
Edited: Image Analyst on 13 Oct 2014
function out = ssort(a,b)
if nargin == 1 || lower(b(1)) == 'u'
out = sort(a, 'Ascend');
else
out = sort(a, 'Descend');
end

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!