Go language will introduce a new sorting algorithm: pdqsort

Original link: Go language will introduce a new sorting algorithm: pdqsort

Hello everyone, I am asong. When I was shopping in the warehouse recently Go, I saw a commitsorting algorithm, that is, the pdqsortsorting algorithm. It is Goplanned to support the sorting algorithm in a version. Let's take a look at this in detail below;

commitAddress: github.com/golang/go/c…

Screenshot 2022-05-06 1.37.10 PM

The test results commitpresented in this:pqdsort

  • pdqsortNot shown to be slower than other previous algorithms in all benchmarks
  • Usually faster in common patterns pdqsort(i.e. 10x faster in sorted slices)

pdqsortIn essence, it is a hybrid sorting algorithm that switches to different sorting mechanisms in different situations. The implementation is inspired by the implementation of C++sum and RUSTis an improvement on the C++standard library algorithm introsort. Its ideal time complexity is O(n) , the worst-case time complexity is O(n*logn), and no additional space is required.

pdqsortThe improvement of the algorithm lies in the special optimization of common situations. The main idea is to continuously determine the current sequence situation, and then use different methods and paths to achieve the optimal solution; if you want to see the specific implementation of the algorithm, you can check https://github.com/zhangyunhao116/pdqsortIn practice, its realization is a continuous cycle of the following three situations:

  • Short sequence case : For input with length [0, MAX_INSERTION], use insertion sort to sort and return directly. Here, MAX_INSERTION is selected as 24 in our performance test in Go language.
  • **Worst case, **If the improved quicksort is found to be ineffective (limit == 0), then heap sort is used for subsequent sorting to ensure the worst case time complexity is O(n*logn).
  • **Normal case,** for other inputs, use modified quicksort to sort

The specific source code implementation can be viewed by yourself. This article will not analyze too much. Let's take a look at pdqsortthe demo:

import (
	"fmt"

	"github.com/zhangyunhao116/pdqsort"
)

func main() {
	x := []int{3, 1, 2, 4, 5, 9, 8, 7}
	pdqsort.Slice(x)
	fmt.Printf("sort_result = %v\n", x)
	search_result := pdqsort.Search(x, 4)
	fmt.Printf("search_result = %v\n", search_result)
	is_sort := pdqsort.SliceIsSorted(x)
	fmt.Printf("is_sort = %v\n", is_sort)
}
复制代码

operation result:

sort_result = [1 2 3 4 5 7 8 9]
search_result = 3
is_sort = true
复制代码

What are your thoughts on this sorting algorithm optimization? Hurry up and experience it.

Reference link:

Well, this article ends here, I'm asong , see you next time.

Welcome to the public account: Golang Dream Factory

Guess you like

Origin juejin.im/post/7098354555636678687