Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion algorithmica/src/sort/heap_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn sink<T: Ord, F: Fn(&T, &T) -> bool>(arr: &mut [T], k: usize, n: usize, p:
let mut k = k;
while 2 * k < n {
let mut j = 2 * k + 1;
if j < n && p(&arr[j], &arr[j + 1]) {
if j + 1 < n && p(&arr[j], &arr[j + 1]) {
Copy link

Copilot AI Apr 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The n parameter is currently used as an inclusive last index (e.g., sort_by passes arr.len() - 1 and decrements l before calling sink). With that contract, the right-child-exists check should be j < n (so j + 1 <= n is in-bounds). Changing this to j + 1 < n skips the right child when it is exactly at index n (e.g., n=6, k=2 => left=5 right=6), which can break the heap property and lead to incorrect sorting. Either revert this condition back to j < n, or change sink’s contract to treat n as an exclusive upper bound/length and update all call sites (sort_by, loop over l, and tests) + add a regression test for the boundary case where right child is at the last index.

Suggested change
if j + 1 < n && p(&arr[j], &arr[j + 1]) {
if j < n && p(&arr[j], &arr[j + 1]) {

Copilot uses AI. Check for mistakes.
j += 1;
}
if !p(&arr[j], &arr[k]) {
Expand Down
Loading