Help on selection sort function
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Maroulator
il 12 Ott 2014
Commentato: Maroulator
il 13 Ott 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 Commenti
the cyclist
il 13 Ott 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?
Risposta accettata
the cyclist
il 13 Ott 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?
0 Commenti
Più risposte (1)
Image Analyst
il 13 Ott 2014
Modificato: Image Analyst
il 13 Ott 2014
function out = ssort(a,b)
if nargin == 1 || lower(b(1)) == 'u'
out = sort(a, 'Ascend');
else
out = sort(a, 'Descend');
end
0 Commenti
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!