算法与体系结构(排序基础-选择排序)

选择排序

1.每次遍历一遍数组,先把数组最小的元素拿出来放到最前面,再进行第二次遍历,再把最小的拿出来

每次选择还没有处理的元素里面最小的

	循环不变量 :arr[i,n)未排序,arr[0,i)

2.时间复杂度:O(n^2)

3.1代码实现(适合于int类型数据):


public class SelectionSort {

    private SelectionSort() {
    }

    public static void sort(int[] arr) {

        for (int i = 0; i < arr.length; i++) {

            //选择arr(i,n]中最小值的索引
            int minIndex = i;
            for (int j = i; j < arr.length; j++) {
                if (arr[j] < arr[minIndex])
                    minIndex = j;
            }

            swap(arr, i ,minIndex);
        }
    }

    private static void swap(int[] arr,int i,int j){

        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args){

        int[] arr = {1,5,2,7,4};
        SelectionSort.sort(arr);
        for (int i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
}

3.2 代码实现(适合于所有数据类型):

public class SelectionSort {

    private SelectionSort() {
    }

    public static <E extends Comparable<E>> void sort(E[] arr) {

        //arr[0,i)是有序的;arr[i,n)是无序的
        for (int i = 0; i < arr.length; i++) {

            //选择arr(i,n]中最小值的索引
            int minIndex = i;
            for (int j = i; j < arr.length; j++) {
                //小于 从小到大;大于 从大到小
                if (arr[j].compareTo(arr[minIndex]) < 0)
                    minIndex = j;
            }

            swap(arr, i ,minIndex);
        }
    }

    private static <E> void swap(E[] arr,int i,int j){

        E t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args){

        //对整形数据进行排序
        Integer[] arr = {1,5,2,7,4};
        SelectionSort.sort(arr);
        for (int i : arr)
            System.out.print(i + " ");
        System.out.println();

        //对特殊对象进行排序
        Student[] students = {new Student("tom",55),
                            new Student("Bob",100),
                            new Student("tom",69)};
        SelectionSort.sort(students);
        for (Student student : students)
            System.out.print(student);
        System.out.println();

        //测试算法性能
        int n = 100000;
        Integer[] arr2 = ArrayGenerator.generatorRandomArray(n,n);

        long startTime = System.nanoTime();
        SelectionSort.sort(arr2);
        long endTime = System.nanoTime();
        double time = endTime - startTime /1000000000.0;

        if (!SortingHelper.isSorted(arr2))
            throw new RuntimeException("SelectionSort Failed");
        System.out.println("time:" + time);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值