Data structure and algorithm (Golang implementation) (20) Sorting algorithm-selection sorting

Select sort

Selection sorting, in general, we refer to simple selection sorting, also called direct selection sorting. It does not exchange elements adjacently like bubble sorting. Instead, it selects the smallest element and only needs to exchange it once per iteration. Although the number of exchanges is much less than bubbling, the efficiency is as bad as bubbling sorting.

Selection sorting is a selection sorting algorithm.

When I play poker, I will habitually scan from left to right, then place the smallest card on the far left, and then continue to scan the second smallest card from left to right from the second card and place it on the smallest On the right side of the card, repeat this. The selection sort is particularly similar to the sort when I play poker.

1. Algorithm introduction

There are a bunch of random number sequence, such as: 5 9 1 6 8 14 6 49 25 4 6 3.

The first iteration, starting from the first number, scans from left to right, finds the smallest number 1, and swaps the position with the first number in the sequence.

The second iteration, starting from the second number, scans from the left to the right, finds the second smallest number 3, and exchanges position with the second number in the sequence.

The third round of iteration, starting from the third number, scans from left to right, finds the third smallest number 4, and exchanges position with the third number in the sequence.

The Nth iteration: ...

After the exchange, the final result is:, 1 3 4 5 6 6 6 8 9 14 25 49we can see that it has been sorted.

Each time you scan the sequence to find the smallest number, and then exchange with the first number, and then exclude the first number, repeat this operation from the second number, this sorting is called simple selection sorting.

For a simple example, choose to sort a 4-element sequence 4 2 9 1:

[]表示排好序

起始: 4 2 9 1  未排序数列从左扫描最小的数是 1,与第一个元素 4 交换,交换 1,4
一轮: [1] 2 9 4 未排序数列从左扫描最小的数是 2,不需要交换
二轮: [1 2] 9 4 未排序数列从左扫描最小的数是 4,与第三个元素 9 交换,交换 4,9
三轮: [1 2 4] 9 未排序数列只有 1 个数,结束
结果: [1 2 4 9]

There are as many comparisons as bubbling sorts, because the scanning process is also a comparison process, but the number of exchanges is reduced to 1 per round. Best and worst time complexity remains: O(n^2).

Selection sorting is an unstable sorting algorithm, such as an array:, the [5 6 5 1]smallest number in the first iteration is 1, then 5exchange the position with the first element , so that the number 1and the number 5exchange position, resulting in two identical numbers 5after sorting The location has changed.

2. Algorithm implementation

package main

import "fmt"

func SelectSort(list []int) {
    n := len(list)
    // 进行 N-1 轮迭代
    for i := 0; i < n-1; i++ {
        // 每次从第 i 位开始,找到最小的元素
        min := list[i] // 最小数
        minIndex := i  // 最小数的下标
        for j := i + 1; j < n; j++ {
            if list[j] < min {
                // 如果找到的数比上次的还小,那么最小的数变为它
                min = list[j]
                minIndex = j
            }
        }

        // 这一轮找到的最小数的下标不等于最开始的下标,交换元素
        if i != minIndex {
            list[i], list[minIndex] = list[minIndex], list[i]
        }
    }
}

func main() {
    list := []int{5, 9, 1, 6, 8, 14, 6, 49, 25, 4, 6, 3}
    SelectSort(list)
    fmt.Println(list)
}

Every iteration, we will maintain the minimum number of this round: minand the subscript of the minimum number:, and minIndexthen start the scan, if the number of scans is smaller than the number, then replace the minimum and minimum subscripts, after scanning determine whether the exchange should then exchange: list[i], list[minIndex] = list[minIndex], list[i].

Three, algorithm improvement

The above algorithm needs to start from a certain number and scan to the end. We can optimize the algorithm to reduce the complexity by half.

In each round, in addition to finding the minimum number, we also find the maximum number, and then exchange with the front and back elements separately, so that the number of cycles is reduced by half, such as:

package main

import "fmt"

func SelectGoodSort(list []int) {
    n := len(list)

    // 只需循环一半
    for i := 0; i < n/2; i++ {
        minIndex := i // 最小值下标
        maxIndex := i // 最大值下标

        // 在这一轮迭代中要找到最大值和最小值的下标
        for j := i + 1; j < n-i; j++ {
            // 找到最大值下标
            if list[j] > list[maxIndex] {
                maxIndex = j // 这一轮这个是大的,直接 continue
                continue
            }
            // 找到最小值下标
            if list[j] < list[minIndex] {
                minIndex = j
            }
        }

        if maxIndex == i && minIndex != n-i-1 {
            // 如果最大值是开头的元素,而最小值不是最尾的元素
            // 先将最大值和最尾的元素交换
            list[n-i-1], list[maxIndex] = list[maxIndex], list[n-i-1]
            // 然后最小的元素放在最开头
            list[i], list[minIndex] = list[minIndex], list[i]
        } else if maxIndex == i && minIndex == n-i-1 {
            // 如果最大值在开头,最小值在结尾,直接交换
            list[minIndex], list[maxIndex] = list[maxIndex], list[minIndex]
        } else {
            // 否则先将最小值放在开头,再将最大值放在结尾
            list[i], list[minIndex] = list[minIndex], list[i]
            list[n-i-1], list[maxIndex] = list[maxIndex], list[n-i-1]
        }
    }
}

func main() {
    list := []int{5}
    SelectGoodSort(list)
    fmt.Println(list)

    list1 := []int{5, 9}
    SelectGoodSort(list1)
    fmt.Println(list1)

    list2 := []int{5, 9, 1}
    SelectGoodSort(list2)
    fmt.Println(list2)

    list3 := []int{5, 9, 1, 6, 8, 14, 6, 49, 25, 4, 6, 3}
    SelectGoodSort(list3)
    fmt.Println(list3)

    list4 := []int{5, 9, 1, 6, 8, 14, 6, 49, 25, 4, 6}
    SelectGoodSort(list4)
    fmt.Println(list4)
}

Output:

[5]
[5 9]
[1 5 9]
[1 3 4 5 6 6 6 8 9 14 25 49]
[1 4 5 6 6 6 8 9 14 25 49]

The optimized sorting is still very slow, it is easy to understand, but it is not recommended for engineering.

Series article entry

I am the star Chen, Welcome I have personally written data structures and algorithms (Golang achieve) , starting in the article to read more friendly GitBook .

Guess you like

Origin www.cnblogs.com/nima/p/12724853.html