필터 지우기
필터 지우기

Help on selection sort function

조회 수: 3 (최근 30일)
Maroulator
Maroulator 2014년 10월 12일
댓글: Maroulator 2014년 10월 13일
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
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?
Maroulator
Maroulator 2014년 10월 13일
Correct; this is a homework assignment that requires me to write my own sort function.

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
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?

추가 답변 (1개)

Image Analyst
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

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by