Created
November 7, 2022 15:30
-
-
Save Deleplace/941082b82d4b2922c638b06c98aed5e4 to your computer and use it in GitHub Desktop.
How much overhead for a STABLE sort of 1000 lowercase letters (26 possible values per letter), compared to a standard sort?
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" | |
) | |
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 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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-> 66% overhead in number of comparisons, when calling
sort.SliceStable
.