【排序算法】选择排序--Java实现

1、基本思想

选择排序是一种简单直观的排序算法,其基本原理如下:对于给定的一组记录,经过第一轮比较后得到最小的记录,然后将该记录的位置与第一个记录的位置交换;接着对不包括第一个记录以外的其他记录进行第二次比较,得到最小记录并与第二个位置记录交换;重复该过程,直到进行比较的记录只剩下一个为止。

2、复杂度分析

从简单选择排序的过程来看,它最大的特点是交换移动数据次数相当少,这样就节约了相应的时间。分析它的时间复杂度发现,无论是最好最差情况,其比较次数都是一样多,第 i 趟排序需要进行 n-i 次关键字比较,此时需要比较这里写图片描述次,对于交换次数而言,当最好的时候,交换0次,最差的时候,也就是初始降时,交换次数为 n-1 次,基于最终的时间排序与交换次数总和,因此,总的时间复杂度依然为这里写图片描述。尽管与冒泡排序同为这里写图片描述,但简单选择排序的性能要优于冒泡排序。

3、选择排序示意图

这里写图片描述

4、Java代码如下

import java.util.Arrays;

public class SelectionSort {

    /**
     * 将最小的元素放在数组最前面
     * @param a
     * 
     */
    public static void selectSort(int[] a) {

        for (int i = 0; i < a.length; i++) {
            int temp = a[i];
            // 将当前下标定义为最小值下标
            int flag = i; 
            for (int j = i + 1; j < a.length; j++) {

                // a[j] < temp 从小到大排序;a[j] > temp 从大到小排序
                if (a[j] < temp) {
                    temp = a[j];
                // 如果有小于当前最小值的关键字将此关键字的下标赋值给flag
                    flag = j; 
                }
            }
            //下标发生变化,元素互换
            if (flag != i) {
                a[flag] = a[i];
                a[i] = temp;
            }
        }
    }

    /**
     * 将数组中最大的元素放在数组末尾 
     * @param list
     *
     */
    public static void selectionSort(int[] list){

        for(int i = list.length - 1;i >= 1;i--){

            //每一趟进行比较时,默认的初始化值
            int currentMax = list[0];
            int currentMaxIndex = 0;

            // 选取数组元素最大值以及元素最大值下标
            for(int j = 1;j <= i;j++){
                if(currentMax < list[j]){
                    currentMax = list[j];
                    currentMaxIndex = j;
                }
            }

            // 当前最大值下标发生改变,最大值与最后一个元素互换
            if(currentMaxIndex != i){
                list[currentMaxIndex] = list[i];
                list[i] = currentMax;
            }
        }
    }

    public static void main(String[] args) {

        int[] sorta={4,7,2,9,6,3};
        int[] sortb={8,7,16,83,26,10,56};
        System.out.println("数组sorta排序前的结果:");
        for(int a:sorta){
            System.out.print(a+" ");
        }
        System.out.println();

        System.out.println("数组sortb排序前的结果:");
        for(int a:sortb){
            System.out.print(a+" ");
        }
        System.out.println();

        selectSort(sorta);
        System.out.println("数组sorta排序后的结果:");
        System.out.println(Arrays.toString(sorta));

        selectionSort(sortb);
        System.out.println("数组sortb排序后的结果:");
        System.out.println(Arrays.toString(sortb));
    }

}

代码运行结果如下:

数组sorta排序前的结果:
4 7 2 9 6 3 
数组sortb排序前的结果:
8 7 16 83 26 10 56 
数组sorta排序后的结果:
[2, 3, 4, 6, 7, 9]
数组sortb排序后的结果:
[7, 8, 10, 16, 26, 56, 83]

猜你喜欢

转载自blog.csdn.net/wilson_m/article/details/80166539