Java选择排序示例

选择排序是就地比较排序。 它循环并找到第一个最小值,并与第一个元素交换; 循环并再次找到第二个最小值,将其与第二个元素交换,重复第三个,第四个,第五个最小值并交换,直到一切都按正确的顺序排列。

PS选择排序在大型列表上效率低下

1.解释

#unsorted data -> [10, 8, 99, 7, 1, 5, 88, 9]

#1 -> [ 10 , 8, 99, 7, 1 , 5, 88, 9] -> [ 1 , 8, 99, 7, 10 , 5, 88, 9]
#2 -> [1, 8 , 99, 7, 10, 5 , 88, 9] -> [1, 5 , 99, 7, 10, 8 , 88, 9]
#3 -> [1, 5, 99 , 7 , 10, 8, 88, 9] -> [1, 5, 7 , 99 , 10, 8, 88, 9]
#4 -> [1, 5, 7, 99 , 10, 8 , 88, 9] -> [1, 5, 7, 8 , 10, 99 , 88, 9]
#5 -> [1, 5, 7, 8, 10 , 99, 88, 9 ] -> [1, 5, 7, 8, 9 , 99, 88, 10 ]
#6 -> [1, 5, 7, 8, 9, 99 , 88, 10 ] -> [1, 5, 7, 8, 9, 10 , 88, 99 ]
#7 -> [1, 5, 7, 8, 9, 10, 88 , 99]  -> [1, 5, 7, 8, 9, 10, 88 , 99]

#result : [1, 5, 7, 8, 9, 10, 88, 99]

这是Java Selection排序实现。

public static void sort(int[] input) {

        int inputLength = input.length;

        for (int i = 0; i < inputLength - 1; i++) {

            int min = i;

            // find the first, second, third, fourth... smallest value
            for (int j = i + 1; j < inputLength; j++) {
                if (input[j] < input[min]) {
                    min = j;
                }
            }

            // swaps the smallest value with the position 'i'
            int temp = input[i];
            input[i] = input[min];
            input[min] = temp;

            //next pls
        }

    }

2. Java选择排序示例

一个完整的示例演示了如何使用选择排序算法对简单数据集进行排序。

SelectionSortExample.java
package com.mkyong;

import java.util.Arrays;

public class SelectionSortExample {

    public static void main(String[] args) {

        int[] array = {10, 8, 99, 7, 1, 5, 88, 9};

        selection_sort(array);

        System.out.println(Arrays.toString(array));

    }

    private static void selection_sort(int[] input) {

        int inputLength = input.length;

        for (int i = 0; i < inputLength - 1; i++) {

            int min = i;

            // find the first, second, third, fourth... smallest value
            for (int j = i + 1; j < inputLength; j++) {
                if (input[j] < input[min]) {
                    min = j;
                }
            }

            // swaps the smallest value with the position 'i'
            int temp = input[i];
            input[i] = input[min];
            input[min] = temp;

            //next pls
        }

    }

}

输出量

[1, 5, 7, 8, 9, 10, 88, 99]

参考文献

  1. 不同种类的排序
  2. 维基百科排序算法–选择排序

翻译自: https://mkyong.com/java/java-selection-sort-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值