Sorting algorithm selection sort (Java version)

Select sort

I was reading "Introduction to Algorithms" recently. As a monk, I really had a headache. First record my experience, a rare good book.
PS: Books that can't be read are good books?

Basic content

Description: Selection sorting is to select the smallest (or largest) element from the data elements to be sorted each time, and store it at the beginning of the sequence until all the data elements to be sorted are arranged.
Selection sort is an unstable sort method.

  • Time complexity: O(n^2)
  • Implementation process: Sort the first element of the array, start from the first element to find the smallest element, exchange the smallest element with the first element after finding, continue to sort the second element, start from the second element to find the smallest element After finding the element, exchange with the second element until one element remains unsorted.

Code

    private void selectionSort(int[] array) {
    
    
        int temp, minIndex;
        //对每个元素进行选择排序
        for (int i = 0; i < array.length; i++) {
    
    
            //将当前位置记录为最小元素位置
            minIndex = i;
            //将当前位置后的元素一一比对,选出最小的元素位置
            for (int j = i + 1; j < array.length; j++) {
    
    
                if (array[j] < array[minIndex]) {
    
    
                    minIndex = j;
                }
            }
            //交换元素,将最小元素插入到当前位置
            temp = array[i];
            array[i] = array[minIndex];
            array[minIndex] = temp;
        }
    }

Conclusion

Set up the flag first: insist on learning algorithms every day.
Next update 归并排序算法.

Guess you like

Origin blog.csdn.net/lijie2664989/article/details/83270507