Data Structures and Algorithms: Selection Sort

principle

From the current position to the end, find the minimum (or maximum) value, place it at the current position, and move the position backward. Then repeat this process.

Each time, the smallest (or largest) value must be found among the remaining unsorted sets and placed at the current position. That’s why it’s called selection sort.

Minimum or maximum affects descending or ascending order.

First time: Find the minimum value in the range of 0 ~ n-1 and place it at position 0.
The second time: Find the minimum value in the range of 1 ~ n-1 and place it at position 1.
The ith time: Find the minimum value in the range of i ~ n-1 and place it at the i position.

Illustration:

Insert image description here

the complexity

Time complexity O(n²)
Additional space complexity O(1)

Code

java version
public static void chooseSort(int[] array) {
    
      
    if (array == null || array.length < 2) {
    
      
        return;  
    }  
  
    for (int i = 0; i< array.length; i ++) {
    
      
        int minIndex = i;  
        for (int j = i + 1; j < array.length; j ++) {
    
      
            if (array[minIndex] > array[j]) {
    
      
                minIndex = j;  
            }  
        }  
        if (minIndex != i) {
    
      
            int temp = array[i];  
            array[i] = array[minIndex];  
            array[minIndex] = temp;  
        }  
    }  
}
Kotlin version
fun chooseSort(array: IntArray) {
    
      
  
        // 只有一个数,或者没有数,不用排序  
        if (array.size < 2) {
    
      
            return  
        }  
  
        var minIndex: Int  
        for (i in array.indices) {
    
      // i 从 0  到 N-1            minIndex = i  
            for (j in (i + 1) until array.size) {
    
      
                minIndex = if (array[j] < array[minIndex]) {
    
      // 找到最小的那个, 这种方式排序出来的,是增序的。  
                    j  
                } else {
    
      
                    minIndex  
                }  
            }  
  
            // 把最小的值换到最前边来。  
            if(minIndex != i) {
    
      
                val temp = array[i]  
                array[i] = array[minIndex]  
                array[minIndex] = temp  
            }  
        }  
    }
Abstract the code that swaps two numbers by multiplying it by a function
fun swap(array: IntArray, indexFrom: Int, indexTo: Int) {
    
      
    if (indexTo != indexFrom) {
    
      
        val temp = array[indexFrom]  
        array[indexFrom] = array[indexTo]  
        array[indexTo] = temp  
    }  
}

Supongo que te gusta

Origin blog.csdn.net/yztbydh/article/details/134985375
Recomendado
Clasificación