排序算法——选择排序(Selection Sort)

排序算法——选择排序(Selection Sort)


算法简介(Introduction)
We start selection sort by scanning entire given list to find its smallest element and exchange it with the first element, putting the smallest element in its final position in sorted list. Then we can scan the list, starting with the second element to find the smallest element among the last n-1 elements and exchange it with the second element, putting the second smallest element in its final position. Basically, in the ith scanning among last n-1-i elements, find the smallest one and exchange with ith element in the list.
这里写图片描述
Left elements has been sorted. Exchange A[i] with A[min].

伪代码(Pseudocode)

function SelectionSort(A[0..n-1])
    for i ⟵ 0 to n-2 do
        min ⟵ i
        for j ⟵ i+1 to n-1 do
            if A[j] < A[min] then
                min ⟵ j
        swap A[i] and A[min]

基本属性(property)
Input: an array A[0..n-1] of n order able items, such as numbers, characters, character strings etc.

Output: an array A[0..n-1] sorted in non-descending order.

In-place: YES. Only requires a constant amount O(1) of additional memory space. Just a little memory for variable i, j, min, tmp(for swap).

Stable: YES. Does not change the relative order of elements with equal keys. For example, A[3]=A[15]=100. The relative order of A[3] and A[15] does not change, which is A[3] is always on the left of A[15].

时间复杂度(Time Complexity)
The size of input is n.
The basic operation is key comparison A[j] < A[min].
The number of times basic operation performed id denoted as Cn.
这里写图片描述
Hence, selection sort is quadratic time.

适用情形(Suitable Situation)
Selection sort performs inefficiently on large list compared with insertion sort due to its O(n^2) time complexity. But it is noted for its simplicity. It is a well-known brute force algorithm.

Java Code

public class Sort{
    //Selection sort method
    public static int[] selectionSort(int[] A){
        int i,j,min,tmp;
        for(i=0;i<A.length-1;i++){
            min=i;
            for(j=i+1;j<A.length;j++)
                if(A[j]<A[min])
                    min=j;
            tmp=A[i];
            A[i]=A[min];
            A[min]=tmp;
        }
        return A;
    }

    //Test
    public static void main(String[] args){
        int[] A={10,15,32,87,90,100,52,67};
        int[] sortedA=Sort.selectionSort(A);
        for(int i=0;i<sortedA.length;i++)
        System.out.print(sortedA[i]+" ");
    }
}

运行结果(Result)

10 15 32 52 67 87 90 100 

写在最后的话(PS)
If you have any question for me, please contact me. My email address is shuaiw6@student.unimelb.edu.au.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值