JAVASE Xiaobai study notes (13-2) array sorting algorithm in Java-selection sort

1. Review bubble sort

We have already introduced bubble sort before,Suppose we want to obtain an ascending sequence of numbers, the principle of bubble sorting is: to compare and exchange each element with the next element, so that the larger element moves to the right like a bubble.Move as shown in the figure below.
Insert picture description here
In this way, each round of operation can move the largest element to the far right. After multiple rounds of operation, the unordered sequence becomes an ascending sequence:
Insert picture description here
But there is an obvious drawback of bubble sorting: too many elements are exchanged. In the world of program operation, although the computer does not produce any "negative emotions", frequent array element exchange means more memory reads and writes. Operation seriously affects the efficiency of code operation.

2. The principle of selection sort

Selection sort: every time an element is compared with each element behind it, the smallest element is placed forward, after a round of comparison, the smallest element will appear at the top, and so on, after a few rounds, the array is sorted just fine Up.

Insert picture description here

3. Select the code implementation of sorting

import java.util.Arrays;
public class MyTest2 {
    
    
    public static void main(String[] args) {
    
    
        //选择排序
        int []arr={
    
    5,8,6,3,9,2,1,7};
        SelectionSort(arr);
    }

    private static void SelectionSort(int[] arr) {
    
    
        for (int i = 0; i < arr.length-1; i++) {
    
    
            int mindex=i;
            for (int j = i+1; j < arr.length; j++) {
    
    
                mindex = arr[mindex] < arr[j] ? mindex : j;
            }
                int temp=arr[i];
                arr[i]=arr[mindex];
                arr[mindex]=temp;
            }
        System.out.println(Arrays.toString(arr));
        }
    }

Guess you like

Origin blog.csdn.net/qq_41537102/article/details/112171469