From f6b737a4e1537cc3bcad766a35312072f98815b3 Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Sat, 21 Nov 2026 20:52:53 +0530 Subject: [PATCH] fix(sort): Bucket panicked when all elements are equal Bucket divided by max - min, which is zero when every element is equal, so sort.Bucket([]int{5, 5}) panicked with an integer divide by zero. Return the slice as it is in that case, and add the case to the shared sort tests. --- sort/bucketsort.go | 6 ++++++ sort/sorts_test.go | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/sort/bucketsort.go b/sort/bucketsort.go index 3f05a41a4..1ad7eabf1 100644 --- a/sort/bucketsort.go +++ b/sort/bucketsort.go @@ -22,6 +22,12 @@ func Bucket[T constraints.Number](arr []T) []T { } } + // all elements are equal, so arr is already sorted + // (and max - min below would be zero) + if max == min { + return arr + } + // create an empty bucket for each element in arr bucket := make([][]T, len(arr)) diff --git a/sort/sorts_test.go b/sort/sorts_test.go index f2394c334..d86e80e20 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -51,6 +51,12 @@ func testFramework(t *testing.T, sortingFunction func([]int) []int) { expected: []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10}, name: "Random order Signed", }, + //All elements equal + { + input: []int{5, 5, 5, 5}, + expected: []int{5, 5, 5, 5}, + name: "All Equal", + }, //Single-entry slice { input: []int{1},