A sort algorithm with bad reputation -- simple selection sort algorithm

Keywords: Java

Simple selection sorting algorithm idea:

Set: sorting interval R [1... N];

  • I n the process of sorting, the whole sorting interval is divided into two sub intervals: ordered region R [1... I-1] and disordered region R [I... N];
  • The minimum record Rmin in the disordered area is selected for each n-1 sorting, and the position of Rmin and the first record in the disordered area is interchanged, so that the length of the disordered area is reduced by 1 and the length of the ordered area is increased by 1.

Select sorting algorithm:

  • Simple selection sorting algorithm
  • Heap sorting algorithm

Algorithm description:

  • Well known sorting algorithm, together with bubbling algorithm, has been in bronze rank double row all the year round.
  • Run time is independent of input.
    • Scanning the smallest elements at a time does not lead to flaws.
    • For example, the sorting time of an ordered array is basically the same as that of an unordered array.
  • Among all sorting algorithms, the number of exchanges is the least.
  • Approximately $\ frac {N^2}{2} $comparisons and \ (N \) exchanges are required.

Realization:

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);
        // Create a random number generator
        Random rand = new Random();
        // Add random integers of 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]

Posted by dimitar on Mon, 30 Mar 2020 22:50:57 -0700