选择排序之简单选择排序

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

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

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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值