A Notorious Sorting Algorithm - Simple Selection Sort

Simple selection sort algorithm idea:

Let: sort interval R[1 ... n];

  • In the process of sorting, the entire sorting interval is divided into two sub-intervals: ordered area R[1 ... i-1]and unordered area R[i ... n];
  • A total of n-1 sorts are performed, and each sort is to select the smallest record in the disordered area Rmin; the Rminposition of the first record in the disordered area is exchanged, so that the length of the disordered area is decreased by 1, and the length of the ordered area is increased by 1.

Selection sort algorithm:

  • Simple Selection Sort Algorithm
  • Heap Sort Algorithm

Algorithm Description:

  • The ranking algorithm with a bad reputation, together with the bubbling algorithm, double-ranked in the bronze rank all the year round.
  • The runtime is independent of the input.
    • Scanning the smallest element per scan does not benefit from micro-defect scanning the smallest element.
    • For example, the sorting time is basically the same for an already ordered array and an unordered array.
  • Among all sorting algorithms, the number of exchanges is the least.
  • It takes about $ \frac {N^2}{2} $ comparisons and \(N\) swaps.

accomplish:

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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689474&siteId=291194637