1024programmer Java GO uses coroutines to improve the efficiency of quick scheduling

GO uses coroutines to improve the efficiency of quick scheduling

After ten years of development, only this Java development system is left
>>> hot3.png

The principle of quick sorting will not be described in detail. The focus here is how to use coroutines to improve quick sorting. Speed:

Quick sort uses the idea of ​​​​divide and conquer. Here the array/slice is divided into two parts. The left part is smaller than the sentinel and the right part is larger than the sentinel. Then the quick sort function is executed recursively. There is a very important point here. The factor is that if a coroutine is used to execute the recursive call, the left half of the array and the right half of the array are passed in as parameters respectively, so there is no need to consider data synchronization issues. The effect is like one coroutine calling 2, two coroutines calling 4, and 4 calling 8. The time complexity will be significantly reduced.

What is the difference between using thread quick sorting and using coroutine quick sorting? Due to system limitations, the creation of threads is limited. Once the array length is large, the speed will be significantly reduced, but coroutines will not , tested a 1 million random number array, and the sorting time was only about 10ms.

The test is as follows:

package main
import "math/rand"
import "fmt"
import "time"

func quickSort(values ​​[]int,left,right int){

i ,j:=left,right

for i<=j{
for j>=p && values[j]>=temp{
if j>=p{

for i<=p && values[i]<=temp{
if i<=p{


values [p]=temp

if p-left>1{
//go quickSort(values,left,p-1)
if right-p>1{
//go quickSort(values,p+1,right)


func QuickSort(values ​​[]int){
func main(){
ceshi := make([]int,10000)
for i:=0 ; i<100; i++ {
start_time :=time.Now ()
end_time :=time.Since(start_time)
fmt.Println("after sort",ceshi)
fmt.Println("count time ",end_time)

The time when coroutine is used is about 1ms, and when coroutine is not used, it takes effect at 40ms. One thing that is not rigorous here is that the two times are different. random array, there will be a little difference, but it is an order of magnitude difference.

Conclusion, using coroutines for quick sorting can significantly improve the speed of quick sorting.


This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/759216

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top