Skip to content

Enhance Library Sort: key/reverse, gap rebalancing, docs - #13392

Closed
leo-soumyajit wants to merge 3 commits into
TheAlgorithms:masterfrom
leo-soumyajit:add-library-sort
Closed

Enhance Library Sort: key/reverse, gap rebalancing, docs#13392
leo-soumyajit wants to merge 3 commits into
TheAlgorithms:masterfrom
leo-soumyajit:add-library-sort

Conversation

@leo-soumyajit

Copy link
Copy Markdown

Title
Enhance: Add Library Sort (gapped insertion) with docs and examples

Summary
Adds an educational, well-documented implementation of Library Sort (gapped insertion) to the sorts directory, including key/reverse parameters, gap rebalancing, and a minimal example script for quick verification. This provides learners with a practical, annotated reference for a distribution-aware insertion strategy.

What’s included
New: sorts/library_sort.py implementing Library Sort with:
key and reverse parameters aligned with Python’s sorting API.
epsilon parameter to control gap density and rebalance behavior.
detailed docstrings and inline comments explaining the data structures (gapped arrays, logical positions) and the rebalance heuristic.
Example: main block demonstrating usage with a small dataset.
Complexity notes in the header docstring: average O(n log n) with high probability, worst O(n^2), space O(n(1+epsilon)).

Motivation
Teaches a lesser-known, research-backed variant of insertion sort that achieves expected O(n log n) by maintaining evenly distributed gaps and rebalancing when clusters form. Ideal for learners comparing practical sort designs beyond classic algorithms.

Implementation notes
Uses a sparse backing array for keys/values plus a “pos” list for logical order; insertions do a binary search on logical order and choose a midpoint slot, rebalancing when local density prevents gap placement.
API mirrors built-in sorted where practical, enabling side-by-side comparison in exercises and tests.

How to test
Run the built-in example:
python sorts/library_sort.py should print a sorted “After:” list.
Sanity checks (suggested):
Compare against sorted on random arrays and edge cases (empty, single element, duplicates).

Verify key and reverse, e.g., key=lambda x: x % 10 and reverse=True.

Scope and trade-offs

Focuses on pedagogy and clarity; not a drop-in replacement for Timsort in production scenarios. For arbitrary real-world data, Python’s built-in sort remains recommended due to stability and adaptiveness.

Library Sort worst case remains O(n^2); documentation calls this out to set correct expectations.

Related

Closes #13203 (advanced sorting algorithms request).

References: Bender et al., “Insertion Sort is O(n log n)” (Library Sort analysis); Wikipedia overview for algorithm characteristics.

@algorithms-keeper

Copy link
Copy Markdown

Closing this pull request as invalid

@leo-soumyajit, this pull request is being closed as none of the checkboxes have been marked. It is important that you go through the checklist and mark the ones relevant to this pull request. Please read the Contributing guidelines.

If you're facing any problem on how to mark a checkbox, please read the following instructions:

  • Read a point one at a time and think if it is relevant to the pull request or not.
  • If it is, then mark it by putting a x between the square bracket like so: [x]

NOTE: Only [x] is supported so if you have put any other letter or symbol between the brackets, that will be marked as invalid. If that is the case then please open a new pull request with the appropriate changes.

@algorithms-keeper algorithms-keeper Bot closed this Oct 9, 2025
@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Oct 9, 2025
@cclauss cclauss reopened this Sep 10, 2026
@algorithms-keeper algorithms-keeper Bot added require descriptive names This PR needs descriptive function and/or variable names require tests Tests [doctest/unittest/pytest] are required labels Sep 10, 2026

@algorithms-keeper algorithms-keeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Click here to look at the relevant links ⬇️

🔗 Relevant Links

Repository:

Python:

Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.

algorithms-keeper commands and options

algorithms-keeper actions can be triggered by commenting on this PR:

  • @algorithms-keeper review to trigger the checks for only added pull request files
  • @algorithms-keeper review-all to trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.

NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.

Comment thread sorts/library_sort.py
import bisect


def library_sort(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function library_sort

Comment thread sorts/library_sort.py
A_vals[mid] = keyed[0][1]
pos.append(mid)

def rebalance(target_count: int) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function rebalance

Comment thread sorts/library_sort.py

A_keys, A_vals, pos = new_keys, new_vals, new_pos

def desired_slot(rank: int) -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function desired_slot

Comment thread sorts/library_sort.py
cap = max(3, int((1.0 + epsilon) * n) + 1)

# Sparse physical storage for keys/values; None marks a gap (empty slot).
A_keys: List[Optional[Tuple]] = [None] * cap

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_keys

Comment thread sorts/library_sort.py

# Sparse physical storage for keys/values; None marks a gap (empty slot).
A_keys: List[Optional[Tuple]] = [None] * cap
A_vals: List[Optional[object]] = [None] * cap

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_vals

Comment thread sorts/library_sort.py
new_vals[new_index] = A_vals[old_idx]
new_pos.append(new_index)

A_keys, A_vals, pos = new_keys, new_vals, new_pos

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_keys

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_vals

Comment thread sorts/library_sort.py
return items.copy()

# Normalize to a key/value representation so we can sort arbitrary objects.
key_fn = key if key is not None else (lambda x: x)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please provide descriptive name for the parameter: x

@algorithms-keeper algorithms-keeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Click here to look at the relevant links ⬇️

🔗 Relevant Links

Repository:

Python:

Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.

algorithms-keeper commands and options

algorithms-keeper actions can be triggered by commenting on this PR:

  • @algorithms-keeper review to trigger the checks for only added pull request files
  • @algorithms-keeper review-all to trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.

NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.

Comment thread sorts/library_sort.py
import bisect


def library_sort(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function library_sort

Comment thread sorts/library_sort.py
A_vals[mid] = keyed[0][1]
pos.append(mid)

def rebalance(target_count: int) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function rebalance

Comment thread sorts/library_sort.py

A_keys, A_vals, pos = new_keys, new_vals, new_pos

def desired_slot(rank: int) -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As there is no test file in this pull request nor any test function or class in the file sorts/library_sort.py, please provide doctest for the function desired_slot

Comment thread sorts/library_sort.py
cap = max(3, int((1.0 + epsilon) * n) + 1)

# Sparse physical storage for keys/values; None marks a gap (empty slot).
A_keys: List[Optional[Tuple]] = [None] * cap

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_keys

Comment thread sorts/library_sort.py

# Sparse physical storage for keys/values; None marks a gap (empty slot).
A_keys: List[Optional[Tuple]] = [None] * cap
A_vals: List[Optional[object]] = [None] * cap

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_vals

Comment thread sorts/library_sort.py
new_vals[new_index] = A_vals[old_idx]
new_pos.append(new_index)

A_keys, A_vals, pos = new_keys, new_vals, new_pos

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_keys

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: A_vals

Comment thread sorts/library_sort.py
return items.copy()

# Normalize to a key/value representation so we can sort arbitrary objects.
key_fn = key if key is not None else (lambda x: x)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please provide descriptive name for the parameter: x

@algorithms-keeper algorithms-keeper Bot added the tests are failing Do not merge until tests pass label Sep 10, 2026
@cclauss cclauss closed this Sep 10, 2026
@algorithms-keeper algorithms-keeper Bot removed the awaiting reviews This PR is ready to be reviewed label Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

invalid require descriptive names This PR needs descriptive function and/or variable names require tests Tests [doctest/unittest/pytest] are required tests are failing Do not merge until tests pass

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Some advance sorting algorithm

2 participants