一种名声不好的排序算法——简单选择排序算

简单选择排序算法思想:

设:排序区间R[1 ... n];

  • 在排序的过程中,整个排序区间被分为两个子区间:有序区R[1 ... i-1]和无序区R[i ... n];
  • 共进行n-1趟排序,每趟排序都是选择无序区的最小记录Rmin;将Rmin与无序区的第一条记录位置互换,使得无序区长度减1,有序区长度增1。

选择排序算法:

  • 简单选择排序算法
  • 堆排序算法

算法说明:

  • 名声不好的排序算法,与冒泡算法一起常年在青铜段位双排。
  • 运行时间与输入无关。
    • 每次扫描最小元素并不会微瑕疵扫描最小元素带来好处 。
    • 比如,已经有序的数组和无序的数组,排序时间基本相同。
  • 所有排序算法中,交换次数是最少的。
  • 大约需要 $ \frac {N^2}{2} $ 次比较和 \(N\) 次交换。

实现:

import java.util.ArrayList;
import java.util.Random;

public class Selection {

    public static void sort(ArrayList<Integer> al) {

        for (int i = 0; i < al.size(); i++) {
            int min = i;
            Integer tempInt = al.get(i);
            for (int j = i + 1; j < al.size(); j++) {
                if (al.get(min) > al.get(j)) {
                    min = j;
                }

            }
            al.set(i, al.get(min));
            al.set(min, tempInt);

            System.out.println(al);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Integer> al = new ArrayList<>(10);
        // 创建一个随机数生成器
        Random rand = new Random();
        // 添加1-100的随机整数
        for (int i = 0; i < 10; i++) {
            al.add(new Integer(Math.abs(rand.nextInt(100))+1));
        }
        System.out.println("The ArrayList Sort Before:\n" + al+"\n");
        Selection.sort(al);
    }

}

Output:

The ArrayList Sort Before:
[81, 39, 13, 56, 27, 100, 98, 97, 68, 37]
sorting:
[13, 39, 81, 56, 27, 100, 98, 97, 68, 37]
[13, 27, 81, 56, 39, 100, 98, 97, 68, 37]
[13, 27, 37, 56, 39, 100, 98, 97, 68, 81]
[13, 27, 37, 39, 56, 100, 98, 97, 68, 81]
[13, 27, 37, 39, 56, 100, 98, 97, 68, 81]
[13, 27, 37, 39, 56, 68, 98, 97, 100, 81]
[13, 27, 37, 39, 56, 68, 81, 97, 100, 98]
[13, 27, 37, 39, 56, 68, 81, 97, 100, 98]
[13, 27, 37, 39, 56, 68, 81, 97, 98, 100]
[13, 27, 37, 39, 56, 68, 81, 97, 98, 100]

猜你喜欢

转载自www.cnblogs.com/LittleTreasureBox/p/8906220.html