Help on selection sort function
8 ビュー (過去 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!