ssort.m

来自「学习Matlab循环语句的好例子」· M 代码 · 共 45 行

M
45
字号
function out=ssort(a)
%ssort selection sort data in ascending order
%function ssort sorts a numeric data set into ascending order.
% Note that the selection sort is relatively inefficient. Don not 
% use this function for large data sets. user matlab's "sort" function
% instead.

%define variables:
% a   ----input array to sort
% ii   ---index variable
% iptr  ---pointer to min value
% jj    ---index variable
% nvals   --number of values in "a"
% out   ---sorted output array
% temp   ----Temp variable for swapping 

% Record of revisionss:
%    Date       programmer         Description of change
% ==========   ============       ======================
%  12/19/98     S.J.Chapman         Original code

% Get the length of the array to sort
nvals=size(a,2);

% Sort the input array
for ii=1:nvals-1
    % Find the minimum value in a(ii) through a(n)
    iptr=ii;
    for jj=ii+1:nvals
        if a(jj)<a(iptr)
            iptr=jj;
        end
    end
    %iptr now points to the minimum value,so swap a(iptr)
    % with a(ii) if ii~=iptr
    if ii~=iptr
        temp=a(ii);
        a(ii)=a(iptr);
        a(iptr)=temp;
    end
end
% Pass data back to caller
out=a;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?