加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

一千万个随机数排序,如何24秒蜕变成3秒?如何从700M内存消耗变成

发布时间:2020-12-16 18:42:00 所属栏目:大数据 来源:网络整理
导读:上一篇文章写的十分的烂,经过科普看语言源码实现用的是quicksort实现的底层排序,在这里模仿一下,勿喷! package mainimport ("fmt""math/rand""runtime""sort""time")func mergeonce(l,r []int) []int {m := make([]int,len(l)+len(r))i,j := 0,0if i len(l)
上一篇文章写的十分的烂,经过科普看语言源码实现用的是quicksort实现的底层排序,在这里模仿一下,勿喷!
package main

import (
	"fmt"
	"math/rand"
	"runtime"
	"sort"
	"time"
)

func mergeonce(l,r []int) []int {
	m := make([]int,len(l)+len(r))
	i,j := 0,0
	if i < len(l) && j < len(r) {
		for {
			if l[i] < l[j] {
				m = append(m,l[i])
				i++
				if i == len(l) {
					break
				}
			} else {
				m = append(m,l[j])
				j++
				if j == len(r) {
					break
				}
			}
		}
	}
	m = append(append(m,l[i:]...),r[j:]...)
	return m
}

func merge(in chan []int,out chan []int) {
	var next chan []int
	var l []int
	for list := range in {
		if l == nil {
			l = list
			continue
		}

		r := list

		if next == nil {
			next = make(chan []int,1)
			go merge(next,out)
		}

		next <- mergeonce(l,r)
		l = nil
	}
	if next == nil {
		out <- l
	} else {
		if l != nil {
			next <- l
		}
		close(next)
	}
}

func main() {
	runtime.GOMAXPROCS(2)
	ch := make(chan []int,1)

	const Num = 100
	const WNum = 100
	fmt.Println(time.Now())
	go func(n int,out chan []int) {
		for i := 0; i < n; i++ {
			list := make([]int,1000)
			for j := range list {
				list[j] = rand.Int()
			}

			sort.Ints(list)
			out <- list
		}
		close(out)
	}(Num*WNum,ch)

	out := make(chan []int)
	go merge(ch,out)
	list := <-out
	fmt.Println(time.Now())
	fmt.Println(len(list))
	fmt.Println(sort.IntsAreSorted(list))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读