选择排序

选择排序

选择最小的一个元素放在第一个位置上,第二小的元素放在第二个位置,以此类推,直到待排序序列排序完成。

排序过程
待排序序列: 4, 6, 3, 1, 8, 9, 3

i = 0; min = 3 : 1, 6, 3, 4, 8, 9, 3
i = 1; min = 2 : 1, 3, 6, 4, 8, 9, 3 
i = 2; min = 6 : 1, 3, 3, 4, 8, 9, 6 
i = 3; min = 3 : 1, 3, 3, 4, 8, 9, 6 
i = 4; min = 6 : 1, 3, 3, 4, 6, 9, 8 
i = 5; min = 6 : 1, 3, 3, 4, 6, 8, 9 
i = 6; min = 6 : 1, 3, 3, 4, 6, 8, 9 
伪代码
    select_sort(A)
        for i = 0 to A.length
            int min = i;
            for j = i+1 to A.length
                if (a[min] > a[j]) min = j;
            temp = a[min];
            a[min] = a[i];
            a[i] = temp; 
Java 实现
/**
 * 选择排序算法
 */
public class SelectionSort {
    //从小到大排序
    public static <T extends Comparable<T>> void selectionSort(T[] a) {
        for (int i = 0; i < a.length; i++) {
            int min = i;
            for (int j = i+1; j < a.length; j++) {
                if (a[min].compareTo(a[j]) > 0) {
                    min = j;
                }
            }
            exchange(a, i, min);

        }
    }

    public static  <T extends Comparable<T>> void exchange(T[] a, int source, int destination) {
        T temp = a[source];
        a[source] = a[destination];
        a[destination] = temp;
    }

    public static void main(String[] args) {
        Integer[] a = {4,6,3,1,8,9,3};
        SelectionSort.selectionSort(a);
        for (Integer item : a) 
            System.out.print(item + ",");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值