内部排序之简单选择排序

1. 算法原理

  简单选择排序(Simple Selection Sort)的实质为,从待排序序列A[i…n]中,选取关键字最小的元素A[x](i<x<=n),放置于已排序序列A[1…i]的末尾位置(A[i])上,即将第i小的元素放置在位置i上。

  

2. 稳定性

  

  排序完成之后,25和25*两个元素的前后位置发生变化,故简单选择排序是不稳定的。

3. 时间复杂度

  简单选择排序的比较次数与初始排序方式无关,若待排序序列中所含元素的个数为N,则比较次数为1+2+…+n-1+n=n*(n-1)/2≈n^2/2,时间复杂度为O(n^2)。

4. 算法程序

function sortedArray = simpleSelectionSort(array, number, sortKind)

% Simple selection sort.
%
% input - array : disordered array.
%         number : the number of array elements.
%         sortKind : kind of sort (1 - positive and 0 -negative).
%
% output - sortedArray : sorted array.

if (number <= 0)
    error('The disordered array empty.');
end

if (number > 1)
    % the number of disordered array is more than 1.
    for index = 1 : number - 1
        % index of the smallest element.
        indexSelect = index;
        
        for i = index + 1 : number
            if (sortKind == 1)
                % positive
                if (array(indexSelect) > array(i))
                    indexSelect = i;
                end
            end
            
            if (sortKind == 0)
                % negative
                if (array(indexSelect) < array(i))
                    indexSelect = i;
                end
            end
        end
        
        if (indexSelect ~= index)
            % exchange elements.
            tempElement = array(index);
            array(index) = array(indexSelect);
            array(indexSelect) = tempElement;
        end
    end
end

sortedArray = array;

5. 视觉直观感受

  

转载于:https://www.cnblogs.com/liekkas0626/p/5227962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值