Last active
November 7, 2022 16:32
-
-
Save Deleplace/034c2a7f682b588628f2ae46c5e08b45 to your computer and use it in GitHub Desktop.
Overhead of stable sorting, in Go
This file contains 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 stablesort | |
import ( | |
"math/rand" | |
"sort" | |
"testing" | |
"golang.org/x/exp/slices" | |
) | |
const ( | |
M = 500 | |
SIZE = 1000 | |
) | |
func TestSlice(t *testing.T) { | |
r := rand.New(rand.NewSource(42)) | |
data := randData(r) | |
comparisons := 0 | |
for k := range data { | |
sort.Slice(data[k], func(i, j int) bool { | |
comparisons++ | |
return data[k][i] < data[k][j] | |
}) | |
} | |
t.Logf("sort.Slice: %d comparisons", comparisons) | |
} | |
func TestSliceStable(t *testing.T) { | |
r := rand.New(rand.NewSource(42)) | |
data := randData(r) | |
comparisons := 0 | |
for k := range data { | |
sort.SliceStable(data[k], func(i, j int) bool { | |
comparisons++ | |
return data[k][i] < data[k][j] | |
}) | |
} | |
t.Logf("sort.SliceStable: %d comparisons", comparisons) | |
} | |
func TestSortFunc(t *testing.T) { | |
r := rand.New(rand.NewSource(42)) | |
data := randData(r) | |
comparisons := 0 | |
for k := range data { | |
slices.SortFunc(data[k], func(a, b rune) bool { | |
comparisons++ | |
return a < b | |
}) | |
} | |
t.Logf("slices.SortFunc: %d comparisons", comparisons) | |
} | |
func TestSortStableFunc(t *testing.T) { | |
r := rand.New(rand.NewSource(42)) | |
data := randData(r) | |
comparisons := 0 | |
for k := range data { | |
slices.SortStableFunc(data[k], func(a, b rune) bool { | |
comparisons++ | |
return a < b | |
}) | |
} | |
t.Logf("slices.SortStableFunc: %d comparisons", comparisons) | |
} | |
func randLetter(r *rand.Rand) rune { | |
return 'a' + rune(r.Intn(26)) | |
} | |
func randData(r *rand.Rand) [][]rune { | |
data := make([][]rune, M) | |
for i := range data { | |
data[i] = make([]rune, SIZE) | |
for j := range data[i] { | |
data[i][j] = randLetter(r) | |
} | |
} | |
return data | |
} | |
func TestData(t *testing.T) { | |
r := rand.New(rand.NewSource(42)) | |
data := randData(r) | |
t.Log(string(data[0][:60])) // Okay this looks like "hrukpttuezptneuvunhuksqvgzadxlgghejkmvezjpmkqakmtrgkfbswyjun" | |
} |
Author
Deleplace
commented
Nov 7, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment