Last active
April 6, 2023 14:57
-
-
Save honmaple/acf9890a073eecc52767eb02e5601f95 to your computer and use it in GitHub Desktop.
insert new element to array and sort compare to search and sort when insert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math/rand" | |
"sort" | |
"testing" | |
"time" | |
) | |
func randNums() []int { | |
rand.Seed(time.Now().Unix()) | |
return rand.Perm(len) | |
} | |
var nums = randNums() | |
var len = 500 | |
func insertSort1() { | |
ss := make([]int, 0, len) | |
for _, num := range nums { | |
ss = append(ss, num) | |
} | |
sort.Ints(ss) | |
} | |
func BenchmarkSort1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
insertSort1() | |
} | |
} | |
func insertSort2() { | |
ss := make([]int, 0, len) | |
for _, num := range nums { | |
i := sort.SearchInts(ss, num) | |
ss = append(ss, 0) | |
copy(ss[i+1:], ss[i:]) | |
ss[i] = num | |
} | |
} | |
func BenchmarkSort2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
insertSort2() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
100
200
500
1000