Help on selection sort function
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
the cyclist
2014-10-13
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?
采纳的回答
the cyclist
2014-10-13
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 个评论
更多回答(1 个)
Image Analyst
2014-10-13
编辑:Image Analyst
2014-10-13
function out = ssort(a,b)
if nargin == 1 || lower(b(1)) == 'u'
out = sort(a, 'Ascend');
else
out = sort(a, 'Descend');
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!