选择排序之简单选择排序

来源:互联网 发布:气宗 剑宗 知乎 编辑:程序博客网 时间:2024/05/29 12:32

选择排序是几大排序算法中的一种,选择排序的思想如下:

每趟从待排序的记录序列中选择关键字最小的记录放置到已排序表的最前位置,直到全部排完。

选择排序大概有两种,今天我们说其中一种——简单选择排序。

1、基本思想:在要排序的一组数中,选出最小的一个数与第一个位置的数交换;然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。

这段话什么意思呢?我们举个例子来说说:

有一个数组{3,5,2,10,1,7},最后的顺序要求是从左到右,从小到大。我们从第一个位置开始,在数组中寻找一个最小的元素,可以发现最小的元素是1,那么就将第一个位置的元素和1交换,交换后的数组是{1,5,2,10,3,7},现在第一个位置就确定,接着从第二个位置开始,在数组中寻找第二小的元素,可以发现是2,那么就将第二个未知的元素和2交换,交换后的数组是{1,2,5,10,3,7},现在第二个位置也就确定了,然后继续直到整个数组都排好。

简单选择排序是稳定的排序方法。简单选择排序的时间复杂度为O(n2)。

下面来看一段实现代码:

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package algorithm;/** * 1、基本思想:在要排序的一组数中,选出最小的一个数与第一个位置的数交换; * 然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。 * 2、适用场景:简单选择排序是不稳定的排序。时间复杂度:T(n)=O(n2)。 */public class SimpleSelectSort {    public void simpleSelectSort(int... args) {        if (args != null && args.length > 0) {            for (int i = 0; i < args.length; i++) {                int min = args[i];                int n = i;                for (int j = i + 1; j < args.length; j++) {                    if (args[j] < min) {                        min = args[j];                        n = j;                    }                }                args[n] = args[i];                args[i] = min;            }        }    }    public static void main(String[] args) {        SimpleSelectSort sss = new SimpleSelectSort();        int[] array = {3, 5, 2, 10, 1, 7};        for (int temp : array) {            System.out.print(temp + " ");        }        System.out.println();        sss.simpleSelectSort(array);        for (int temp : array) {            System.out.print(temp + " ");        }    }}


0 0
原创粉丝点击