Sorting algorithm - selection sort (Java)

package com.rao.linkList;

import java.util.Arrays;

/**
 * @author Srao
 * @className SelectSort
 * @date 2019/12/4 11:27
 * @package com.rao.linkList
 * @Description 选择排序
 */
public class SelectSort {
    /**
     * 选择排序
     * @param arr
     */
    public static void selectSort(int[] arr){
        for (int i = 0; i < arr.length-1; i++){
            int min = i;
            for (int j = i; j <= arr.length-1; j++){
                if (arr[j] < arr[min]){
                    min = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{3,6,2,5,9,1,0,8};
        System.out.println(Arrays.toString(arr));
        selectSort(arr);
        System.out.println(Arrays.toString(arr));

    }
}

First, find the smallest element in the array, and secondly, it will be the first element of the array and swap positions (if the first element is the smallest element and then it own exchange).

Second, find the smallest element in the rest of the elements, it will be the second element of the array exchange position.

And so on.

Guess you like

Origin www.cnblogs.com/rao11/p/11982016.html