Skip to content

fix(sort): Bucket panicked when all elements are equal - #817

Open
JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-bucket-sort-equal-elements
Open

JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-bucket-sort-equal-elements

Conversation

@JayPokale

Copy link
Copy Markdown

Description of Change

sort.Bucket computes the bucket index with (v - min) / (max - min). When every element is equal, max - min is zero: sort.Bucket([]int{5, 5}) panics with integer divide by zero (and with floats the index becomes NaN). The slice is already sorted in that case, so it is returned as it is, before the buckets are built.

I added an "All Equal" case to the shared testFramework in sort/sorts_test.go. It fails for TestBucketSort on master (panic) and passes for all other sorts, which I also checked with a throwaway comparison against sort.Ints on random slices with duplicates and negative values (the other sorts agree). go test ./sort, go vet ./sort and gofmt -l sort pass.

Written with the help of Claude Code (Claude Sonnet 5.5).

Checklist

  • Added description of change
  • Added file name matches File name guidelines
  • Added tests and example, test must pass
  • Added documentation so that the program is self-explanatory and educational - GoDoc guidelines
  • Relevant documentation/comments is changed or added
  • PR title follows semantic commit guidelines
  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • I acknowledge that all my contributions will be made under the project's license.

Notes: no new files; the only change to behaviour is that equal-element input no longer panics.

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.
@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 9 complexity · 0 duplication

Metric Results
Complexity 9
Duplication 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant