Sorting algorithm---selection sorting (java version)

Simple selection sort

principle

The principle of selection sort (Selection Sort) is a bit similar to insertion sort, and it is also divided into sorted and unsorted intervals. But the selection sort will find the smallest element from the sorting interval every time and place it at the end of the sorted interval.

The simple selection and sorting execution process is implemented by the code as shown in the figure below
Insert picture description here

public class SelectSort {
    
    
    public static void main(String[] args) {
    
    
        int arr[] = {
    
    34,1,139,101};
        for (int i = 0; i < arr.length; i++) {
    
    
            int minIndex = i;
            int min = arr[i];
            for (int j = i + 1; j < arr.length; j++) {
    
    
                //找最小值
                if (min > arr[j]) {
    
    
                    //如果最初的min值比后面的值大,说明不是最小值,重置min值,直到找到对应位置最小的min值
                    min = arr[j];
                    minIndex = j;
                }
            }
            //先找到对应位置的最小值,再将找到的最小值与最初的值进行交换
            //将最小值与最初的值进行交换
            if (minIndex != i) {
    
    
                arr[minIndex] = arr[i];
                arr[i] = min;
            }
            System.out.println(Arrays.toString(arr));
        }
    }
}

1: What is the time complexity of the selection sort?

Combined with the analysis of the previous analysis methods, it can be seen that the time complexity of the best case of selection and sorting is O(n^2), the worst case time complexity is: O(n^2), and the time complexity of the average case is: O( n ^2).

2: What is the space complexity of the selection sort?

Through the implementation of the algorithm, we can find that the space complexity of selection sorting is O(1), which is an in-place sorting algorithm.

3: Is selective sorting a stable sorting algorithm?

Selection sorting is not a stable sorting algorithm, because selection sorting always finds the smallest value among the remaining unsorted elements and swaps positions with the first element of the unsorted range, which destroys stability, such as 5, 8. ,5,2,9 such a set of data, if you use the selection sort algorithm to sort, the smallest element 2 is found for the first time, and the position of the first 5 is exchanged, then the order of the first 5 and the middle 5 will change, so It becomes unstable. For this reason, selection sorting is slightly inferior to bubble sorting and insertion sorting in terms of stability.

Guess you like

Origin blog.csdn.net/qq_33626996/article/details/113178888