Sort ----- selection sort (java)

One: what is selection sort

    Simplest sorting algorithm, first find the smallest value from the array, swap it with the first element (and with itself if the first element is the smallest). Find the smallest element among the remaining elements and swap with the second element. Repeat in sequence until the entire array is sorted.    

Two: sorting process

    

        For each sorting, we will determine a minimum value and place it at the i-th position. The sorting only needs to be performed a.length-1 times, because there is only one element left at the a.length time, and no comparison is required.

    Selection sort is relatively easy to understand and implement, and has distinct specificities:

    1. Running time is independent of input.

        Sorting takes the same amount of time regardless of the input state of the array, ordered, unordered, or the primary key is all equal.

    2. Data movement is minimal

          At the end of the entire sorting, only N exchanges are required, and the number of moves is the smallest compared with other sorting algorithms.

Three: code implementation

public class SelectSort {
    public static void main(String args[]){
        int a[] = {10,23,5,2,112,34,22,99,0,45,1};
        sort(a);
        show(a);
    }
    private static void show(int[] a) {
        System.out.println("Sort result");
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }
    public static void sort(int[] a){
        for(int i=0;i<a.length-1;i++){
            int min = i;
            for(int j=i+1;j<a.length;j++){
                if(less(a,j,min)){
                    min = j;
                }
            }
            exch(a,i,min);
        }
    }
    /**Data exchange*/
    private static void exch(int[] a, int i, int min) {
        int temp = a[i];
        a [i] = a [min];
        a[min] = temp;
    }
    /**Data comparison*/
    private static boolean less(int[] a, int j, int min) {
        if(a[j] > a[min]){
            return false;
        }else{
            return true;
        }
    }
}

Sort results:

    

Guess you like

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