Golang implements quick sort

1. Thought

Taking ascending order as an example, a certain number in the array (sub-array) is selected as a key in each pass, and the number in the array that is smaller than the key is moved to the left of the key, and the number that is greater than the key is moved to the right of the key. When the sorting is completed, the key will be moved to the correct position, and the array will be divided into two smaller sub-arrays, with the sub-array as the initial array, and then repeat the above operations.

Two, the code

package main

import "fmt"

func QuickSort(data []int, low int, high int)  {
    
    
	if len(data) < 2 || data == nil{
    
    
		return
	}
	i, j := low, high
	temp := data[i]
	for {
    
    
		for i < j {
    
    
			if data[j] <= temp {
    
    
				data[i] = data[j]
				break
			}
			j--
		}
		for i < j{
    
    
			if data[i] > temp{
    
    
				data[j] = data[i]
				break
			}
			i++
		}
		if i >= j{
    
    
			data[i] = temp
			break
		}
	}
	if i - 1 > low{
    
    
		QuickSort(data, low, i - 1)
	}
	if i + 1 < high{
    
    
		QuickSort(data, i + 1, high)
	}
}
func main()  {
    
    
	arr := []int{
    
    49, 38, 65, 97, 76, 13, 27, 49}
	QuickSort(arr, 0, len(arr) - 1)
	fmt.Println(arr)
}
[13 27 38 49 49 65 76 97]

Process finished with exit code 0

3. Performance Analysis

The more ordered the array, the lower the efficiency, the time complexity is:
0 ( n 2 ) 0(n^2)0(n2 )
The more unordered the array, the higher the efficiency, and the time complexity is:
0 ( n log ⁡ 2 n ) 0(n\log_2 n)0(nlog2n )
The average time complexity is:
0 ( n log ⁡ 2 n ) 0(n\log_2 n)0(nlog2n )
space complexity is:
0 ( log ⁡ 2 n ) 0(\log_2 n)0(log2n)

Guess you like

Origin blog.csdn.net/QQ395879676/article/details/116032716