排序算法之选择排序

作者: 就叫吴昊 | 来源:发表于2018-03-15 17:08 被阅读28次

选择排序法(selection sort)

来自维基百科
选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
选择排序的主要优点与数据移动有关。如果某个元素位于正确的最终位置上,则它不会被移动。选择排序每次交换一对元素,它们当中至少有一个将被移到其最终位置上,因此对n个元素的表进行排序总共进行至多n-1次交换。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。

选择排序算法

Selection Sort:
Set current to the index of first item in the list
While (not sorted yet)
    Find the index of the smallest unsorted item
    Swap the current item with the smallest unsorted one
    Increment current to shrink unsorted part

Java实现

这里的算法实现是我自己通过自己的理解用Java写的,如有纰漏,错误或不合理的地方还请大家指出并包涵

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class SelectionSort{
    public static void main(String[] args) {
        List<Integer> notSorted = new ArrayList<Integer>();
        notSorted.add(44);
        notSorted.add(34);
        notSorted.add(14);
        notSorted.add(54);
        notSorted.add(24);

        int index = 0;
        while (index < notSorted.size()){

            //Find the index of the smallest unsorted item
            int minIndex = notSorted.indexOf(Collections.min(notSorted.subList(index, notSorted.size())));

            //Swap the current item with the smallest unsorted one
            int temp = notSorted.get(index);
            notSorted.set(index, notSorted.get(minIndex));
            notSorted.set(minIndex, temp);

            index++;

            System.out.println("-------------");
            for (int i = 0; i < notSorted.size(); i++) {
                System.out.println(notSorted.get(i));
            }
        }
    }
}

这里的输出结果是每循环一次就输出一次,以方便理解排序的具体过程。

最后希望能对大家在理解选择排序算法上有所帮助。

相关文章

  • 算法-选择排序

    算 法:选择排序算法时间复杂度: 选择排序算法概述 选择排序伪代码 选择排序实现 选择排序算法概述 排序算法有许...

  • 算法理解之排序-选择排序

    算法理解之排序-选择排序 选择排序是一种简单直观的排序算法, 以当前点为锚点, 向后依次进行比较所有未排序元素, ...

  • 经典排序算法总结

    经典排序算法集锦 冒泡法 排序算法入门之冒泡排序 排序算法入门之冒泡排序优化

  • 3.1-选择排序-简单选择排序

    参考链接 选择排序:简单选择排序(Simple Selection Sort) 白话经典算法系列之四 直接选择排序...

  • JS实现排序算法

    原文:常见排序算法之JavaScript实现 - 知乎 目录 冒泡排序 选择排序 插入排序 合并排序 快速排序 1...

  • 算法4:插入排序和选择排序算法的比较

    排序算法列表电梯: 选择排序算法:详见 《算法4》2.1 - 选择排序算法(Selection Sort), Py...

  • 图形化排序算法比较:快速排序、插入排序、选择排序、冒泡排序

    图形化排序算法比较:快速排序、插入排序、选择排序、冒泡排序 图形化排序算法比较:快速排序、插入排序、选择排序、冒泡排序

  • PHP常用算法

    基于选择的排序算法 常见的基于选择的排序算法有:冒泡排序、插入排序、选择排序、归并排序和快速排序,我们在选在排序算...

  • 算法and数据结构

    算法 冒泡排序 选择排序 计数排序

  • 基础排序算法总结

    排序算法分为内部排序和外部排序,而我们经常说的基础排序算法,都是内部排序算法。包括冒泡排序,选择排序,插入排序,快...

网友评论

    本文标题:排序算法之选择排序

    本文链接:https://www.haomeiwen.com/subject/ycbhqftx.html