Skip to content

Create sorting script #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Create sorting script #13

wants to merge 2 commits into from

Conversation

atharvsabdeai
Copy link

@atharvsabdeai atharvsabdeai commented Jul 23, 2025

Summary by CodeRabbit

  • New Features
    • Added multiple sorting algorithm options, including bubble sort, selection sort, insertion sort, and merge sort.
    • Provided examples demonstrating and comparing the results of each sorting method alongside Python's built-in sorting functions.
  • Refactor
    • Improved event data handling with enhanced error reporting and streamlined main execution flow.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

Copy link

coderabbitai bot commented Jul 23, 2025

Walkthrough

A new Python module named sorting.py has been added, providing implementations for bubble sort, selection sort, insertion sort, and merge sort algorithms. The module also demonstrates usage of these algorithms alongside Python's built-in sorting functions, with output printed for comparison. Additionally, main.py has been refactored to introduce a new function load_github_event() that loads and parses a GitHub event JSON file, with improved error handling, while simplifying the main() function.

Changes

File(s) Change Summary
sorting.py Added with in-place bubble, selection, and insertion sort functions; merge sort (non-in-place) and merge helper; includes sample usage and comparison with Python's built-in sort methods.
main.py Refactored to add load_github_event() function for reading and parsing GitHub event JSON with error handling; simplified main() to call this function and print event data.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant sorting.py
    User->>sorting.py: Call bubble_sort(arr)
    User->>sorting.py: Call selection_sort(arr)
    User->>sorting.py: Call insertion_sort(arr)
    User->>sorting.py: Call merge_sort(arr)
    sorting.py->>sorting.py: merge(left, right) (from merge_sort)
    User->>sorting.py: Use .sort() and sorted() for comparison
Loading
sequenceDiagram
    participant Script
    participant Env
    participant FileSystem
    participant JSONParser

    Script->>Env: Read GITHUB_EVENT_NAME, GITHUB_EVENT_PATH
    Script->>FileSystem: Check if event file exists
    alt File exists
        Script->>FileSystem: Open event file (UTF-8)
        FileSystem->>Script: File content
        Script->>JSONParser: Parse JSON content
        JSONParser->>Script: Parsed event data
        Script->>Script: Return event data
    else File missing or error
        Script->>Script: Print error and exit
    end
    Script->>User: Print event name and event JSON payload
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the meadow of code, where algorithms play,
Four sorts hop in—each with their own way.
Bubble and selection, insertion in line,
Merge splits and joins—oh, how they shine!
The rabbit applauds with a joyful cheer,
"Sorting success—springtime is here!" 🐇✨

Meanwhile, a script reads events with care,
Parsing JSON from GitHub's lair.
Errors caught, neat and clear,
The rabbit nods, "All is here!" 🐰📜

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch atharvsabdeai-patch-2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @atharvsabdeai, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new Python script that implements and showcases several fundamental sorting algorithms. The script provides clear, runnable examples for each algorithm, allowing users to easily understand their behavior and compare them with Python's built-in sorting capabilities.

Highlights

  • New Script for Sorting Algorithms: A new Python file, sorting.py, has been added to the repository, dedicated to demonstrating various sorting algorithms.
  • Multiple Sorting Implementations: The script includes distinct, self-contained implementations for Bubble Sort, Selection Sort, Insertion Sort, and Merge Sort (along with its merge helper function).
  • Algorithm Demonstration and Comparison: Each implemented sorting algorithm is demonstrated with a sample list, and its sorted output is printed. The script also includes examples of Python's native list.sort() and sorted() functions for comparison.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new Python script with implementations of several common sorting algorithms. The implementations are functionally correct. My review provides feedback on improving the script's reusability, maintainability, and efficiency. Key suggestions include adding a __main__ guard, refactoring the repetitive test code, adding type hints for clarity, and noting a memory-efficiency improvement for the merge sort algorithm.

Comment on lines +82 to +121
# Sample input
original = [6, 6, 2, 3, 2]

print("Original list:")
print(original)

# Bubble Sort
arr1 = original.copy()
bubble_sort(arr1)
print("\nBubble Sort result:")
print(arr1)

# Selection Sort
arr2 = original.copy()
selection_sort(arr2)
print("\nSelection Sort result:")
print(arr2)

# Insertion Sort
arr3 = original.copy()
insertion_sort(arr3)
print("\nInsertion Sort result:")
print(arr3)

# Merge Sort (not in-place)
arr4 = original.copy()
arr4_sorted = merge_sort(arr4)
print("\nMerge Sort result:")
print(arr4_sorted)

# Python built-in sort (in-place)
arr5 = original.copy()
arr5.sort()
print("\nPython .sort() result:")
print(arr5)

# Python built-in sorted() (returns new list)
arr6 = sorted(original)
print("\nPython sorted() result (non-in-place):")
print(arr6)

Choose a reason for hiding this comment

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

critical

This block of code has two issues that should be addressed:

  1. Critical: The demonstration code runs in the global scope. This is a significant issue because if another module imports this file, the demonstration code will execute unexpectedly. All script execution logic should be placed within an if __name__ == "__main__": block to ensure the module is reusable.
  2. Medium: The code for testing each sorting algorithm is highly repetitive. This violates the Don't Repeat Yourself (DRY) principle and makes the code harder to maintain or extend. Refactoring this into a loop would make it much cleaner.

Here is a suggested refactoring that addresses both points by organizing the tests and placing them inside a __main__ guard:

if __name__ == "__main__":
    # Sample input
    original = [6, 6, 2, 3, 2]

    print("Original list:")
    print(original)

    # Sorting functions to test: (name, function, is_in_place)
    sorting_algorithms = [
        ("Bubble Sort", bubble_sort, True),
        ("Selection Sort", selection_sort, True),
        ("Insertion Sort", insertion_sort, True),
        ("Merge Sort", merge_sort, False),
        ("Python .sort()", lambda arr: arr.sort(), True),
        ("Python sorted()", sorted, False),
    ]

    for name, sort_func, is_in_place in sorting_algorithms:
        arr_copy = original.copy()
        print(f"\n{name} result:")
        if is_in_place:
            sort_func(arr_copy)
            print(arr_copy)
        else:
            sorted_arr = sort_func(arr_copy)
            print(sorted_arr)

@@ -0,0 +1,121 @@
def bubble_sort(arr):

Choose a reason for hiding this comment

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

medium

To improve code clarity, maintainability, and enable static analysis, consider adding type hints to your function signatures, as recommended by PEP 484. This should be applied to all functions in this file.

For example, bubble_sort takes a list and modifies it in-place, so its return type is None. You can use the built-in list type for basic hinting. For more specific types (e.g., a list of numbers), you might use from typing import List, Union and annotate as List[Union[int, float]].

Suggested change
def bubble_sort(arr):
def bubble_sort(arr: list) -> None:

Comment on lines +54 to +55
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])

Choose a reason for hiding this comment

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

medium

The current implementation of merge_sort creates new sub-lists using slicing (arr[:mid] and arr[mid:]) in each recursive call. For large lists, this can be inefficient and consume a lot of memory because Python creates a copy of the data for each slice. A more memory-efficient approach for merge_sort is to pass indices (e.g., start and end) to the recursive calls. This allows them to work on views of the original list (or a single copy) instead of creating many small, temporary copies.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
sorting.py (2)

17-28: Optimize to avoid unnecessary swaps.

The selection sort implementation is correct, but it performs unnecessary swaps when the minimum element is already in the correct position.

Consider adding a condition to avoid swapping when min_idx == i:

-        arr[i], arr[min_idx] = arr[min_idx], arr[i]
+        if min_idx != i:
+            arr[i], arr[min_idx] = arr[min_idx], arr[i]

82-122: Good demonstration code with minor formatting fix needed.

The sample usage effectively demonstrates all sorting algorithms and properly preserves the original array using copy(). The comparison with Python's built-in sorting functions adds educational value.

Add a newline at the end of the file for better formatting:

 print("Python sorted() result (non-in-place):")
 print(arr6)
+
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e184110 and 2d90535.

📒 Files selected for processing (1)
  • sorting.py (1 hunks)
🔇 Additional comments (4)
sorting.py (4)

1-14: LGTM! Well-implemented bubble sort with optimization.

The bubble sort implementation is correct and includes the early exit optimization when no swaps occur, which improves best-case performance from O(n²) to O(n).


31-42: LGTM! Correct insertion sort implementation.

The insertion sort implementation is accurate and follows the standard algorithm correctly with proper bounds checking and element shifting.


45-57: LGTM! Correct merge sort implementation.

The merge sort implementation is accurate with proper base case handling and recursive structure. The algorithm correctly maintains O(n log n) time complexity.


60-79: LGTM! Correct merge helper function.

The merge function correctly implements the two-pointer technique with proper handling of remaining elements and maintains stability by using <= in the comparison.

Copy link

refacto-test bot commented Jul 23, 2025

🤖 Refacto.AI: PR Summary & Reviewer Guide

Warning: Requirements context (e.g., linked ticket) was not provided. Analysis is based solely on PR metadata and code diff, which may be incomplete.

🎯 1. The Goal (Why was this PR raised?)

This PR aims to create a new Python script that implements and demonstrates various sorting algorithms. The implementation includes bubble sort, selection sort, insertion sort, and merge sort, along with examples of Python's built-in sorting methods.

🗺️ 2. The Changes (What was implemented?)

File Name Implementation Details Goal / Requirement Addressed
sorting.py (Added) Added a new Python script that implements four sorting algorithms:
- bubble_sort: In-place algorithm with early stopping
- selection_sort: In-place algorithm that repeatedly selects minimum elements
- insertion_sort: In-place algorithm that builds sorted array one item at a time
- merge_sort: Recursive divide-and-conquer algorithm (not in-place)

The script also includes a merge helper function and demonstration code that applies each algorithm to a sample list.
Create sorting algorithm implementations

🤔 3. Key Areas for Human Review

Area of Concern: Merge Sort Implementation

  • File: sorting.py (Lines 44-79)
  • Why: The merge sort implementation creates new lists during recursion which can lead to memory inefficiency for large datasets. This is different from the other in-place sorting algorithms in the file.
  • Testing Instruction: Test the merge_sort function with a large array (1000+ elements) and monitor memory usage to ensure it performs within acceptable limits.

Area of Concern: Algorithm Correctness

  • File: sorting.py (Lines 1-79)
  • Why: The sorting algorithms need to correctly handle edge cases like duplicate values, which are present in the test case [6, 6, 2, 3, 2].
  • Testing Instruction: Verify that all implemented sorting algorithms produce the same output as Python's built-in sort functions. Consider testing with additional edge cases like empty lists, single-element lists, and lists with all identical elements.

Area of Concern: Early Termination in Bubble Sort

  • File: sorting.py (Lines 1-14)
  • Why: The bubble sort implementation includes an optimization to stop early if no swaps occur in a pass, which affects its best-case performance.
  • Testing Instruction: Test the bubble_sort function with an already sorted list to verify that it terminates after the first pass (O(n) best case) rather than completing all passes (O(n²)).

Copy link

refacto-test bot commented Jul 23, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 23, 2025

/refacto-test

13 similar comments
@arvi18
Copy link
Collaborator

arvi18 commented Jul 23, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 23, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 23, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 23, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

PR already reviewed at the latest commit: 2d90535.
Please try again with new changes.

Copy link

refacto-test bot commented Jul 24, 2025

No review comments were generated during this review iteration of the PR.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
main.py (1)

5-27: Excellent refactoring with comprehensive error handling.

The load_github_event() function effectively separates concerns and provides robust error handling with clear, user-friendly messages. The implementation correctly validates environment variables, file existence, and handles JSON parsing errors.

Consider refactoring to raise exceptions instead of calling sys.exit() directly within the function, which would make it more testable and reusable:

def load_github_event():
    event_name = os.getenv("GITHUB_EVENT_NAME", "UNKNOWN_EVENT")
    event_path = os.getenv("GITHUB_EVENT_PATH")

    print(f"📦 Received GitHub event: {event_name}")

    if not event_path:
-        print("⚠️  Environment variable GITHUB_EVENT_PATH is not set. Cannot read event data.")
-        sys.exit(1)
+        raise ValueError("Environment variable GITHUB_EVENT_PATH is not set. Cannot read event data.")

    if not os.path.isfile(event_path):
-        print(f"❌ Event file not found at: {event_path}")
-        sys.exit(1)
+        raise FileNotFoundError(f"Event file not found at: {event_path}")

    try:
        with open(event_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except json.JSONDecodeError as e:
-        print(f"❌ Failed to parse event JSON: {e}")
+        raise ValueError(f"Failed to parse event JSON: {e}") from e
    except Exception as e:
-        print(f"❌ Unexpected error reading event file: {e}")
-    
-    sys.exit(1)
+        raise RuntimeError(f"Unexpected error reading event file: {e}") from e

Then handle the exceptions in main() with appropriate error messages and exit codes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d90535 and aea4ef5.

📒 Files selected for processing (1)
  • main.py (1 hunks)
🔇 Additional comments (3)
main.py (3)

3-3: LGTM!

The sys import is correctly added and necessary for the sys.exit() calls in error handling.


29-32: Clean and focused main function.

The refactored main() function is well-structured, focusing solely on the primary workflow while delegating event loading to the dedicated function. The JSON pretty-printing with indent=2 improves readability.


35-35: LGTM!

The main execution follows the standard Python idiom correctly.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

PR already reviewed at the latest commit: aea4ef5.
Please try again with new changes.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

1 similar comment
@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

1 similar comment
@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

1 similar comment
Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

# Python built-in sorted() (returns new list)
arr6 = sorted(original)
print("\nPython sorted() result (non-in-place):")
print(arr6)
Copy link

Choose a reason for hiding this comment

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

critical

This block of code has two issues that should be addressed:

  1. Critical: The demonstration code runs in the global scope. This is a significant issue because if another module imports this file, the demonstration code will execute unexpectedly. All script execution logic should be placed within an if __name__ == "__main__": block to ensure the module is reusable.
  2. Medium: The code for testing each sorting algorithm is highly repetitive. This violates the Don't Repeat Yourself (DRY) principle and makes the code harder to maintain or extend. Refactoring this into a loop would make it much cleaner.

Here is a suggested refactoring that addresses both points by organizing the tests and placing them inside a __main__ guard:

if __name__ == "__main__":
    # Sample input
    original = [6, 6, 2, 3, 2]

    print("Original list:")
    print(original)

    # Sorting functions to test: (name, function, is_in_place)
    sorting_algorithms = [
        ("Bubble Sort", bubble_sort, True),
        ("Selection Sort", selection_sort, True),
        ("Insertion Sort", insertion_sort, True),
        ("Merge Sort", merge_sort, False),
        ("Python .sort()", lambda arr: arr.sort(), True),
        ("Python sorted()", sorted, False),
    ]

    for name, sort_func, is_in_place in sorting_algorithms:
        arr_copy = original.copy()
        print(f"\n{name} result:")
        if is_in_place:
            sort_func(arr_copy)
            print(arr_copy)
        else:
            sorted_arr = sort_func(arr_copy)
            print(sorted_arr)

@arvi18
Copy link
Collaborator

arvi18 commented Jul 24, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 24, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

# Python built-in sorted() (returns new list)
arr6 = sorted(original)
print("\nPython sorted() result (non-in-place):")
print(arr6)
Copy link

Choose a reason for hiding this comment

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

critical

This block of code has two issues that should be addressed:

  1. Critical: The demonstration code runs in the global scope. This is a significant issue because if another module imports this file, the demonstration code will execute unexpectedly. All script execution logic should be placed within an if __name__ == "__main__": block to ensure the module is reusable.
  2. Medium: The code for testing each sorting algorithm is highly repetitive. This violates the Don't Repeat Yourself (DRY) principle and makes the code harder to maintain or extend. Refactoring this into a loop would make it much cleaner.

Here is a suggested refactoring that addresses both points by organizing the tests and placing them inside a __main__ guard:

if __name__ == "__main__":
    # Sample input
    original = [6, 6, 2, 3, 2]

    print("Original list:")
    print(original)

    # Sorting functions to test: (name, function, is_in_place)
    sorting_algorithms = [
        ("Bubble Sort", bubble_sort, True),
        ("Selection Sort", selection_sort, True),
        ("Insertion Sort", insertion_sort, True),
        ("Merge Sort", merge_sort, False),
        ("Python .sort()", lambda arr: arr.sort(), True),
        ("Python sorted()", sorted, False),
    ]

    for name, sort_func, is_in_place in sorting_algorithms:
        arr_copy = original.copy()
        print(f"\n{name} result:")
        if is_in_place:
            sort_func(arr_copy)
            print(arr_copy)
        else:
            sorted_arr = sort_func(arr_copy)
            print(sorted_arr)

@@ -0,0 +1,121 @@
def bubble_sort(arr):
Copy link

Choose a reason for hiding this comment

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

medium

To improve code clarity, maintainability, and enable static analysis, consider adding type hints to your function signatures, as recommended by PEP 484. This should be applied to all functions in this file.

For example, bubble_sort takes a list and modifies it in-place, so its return type is None. You can use the built-in list type for basic hinting. For more specific types (e.g., a list of numbers), you might use from typing import List, Union and annotate as List[Union[int, float]].

Suggested change
def bubble_sort(arr):
def bubble_sort(arr: list) -> None:


mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
Copy link

Choose a reason for hiding this comment

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

medium

The current implementation of merge_sort creates new sub-lists using slicing (arr[:mid] and arr[mid:]) in each recursive call. For large lists, this can be inefficient and consume a lot of memory because Python creates a copy of the data for each slice. A more memory-efficient approach for merge_sort is to pass indices (e.g., start and end) to the recursive calls. This allows them to work on views of the original list (or a single copy) instead of creating many small, temporary copies.

# Python built-in sorted() (returns new list)
arr6 = sorted(original)
print("\nPython sorted() result (non-in-place):")
print(arr6)
Copy link

Choose a reason for hiding this comment

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

critical

This block of code has two issues that should be addressed:

  1. Critical: The demonstration code runs in the global scope. This is a significant issue because if another module imports this file, the demonstration code will execute unexpectedly. All script execution logic should be placed within an if __name__ == "__main__": block to ensure the module is reusable.
  2. Medium: The code for testing each sorting algorithm is highly repetitive. This violates the Don't Repeat Yourself (DRY) principle and makes the code harder to maintain or extend. Refactoring this into a loop would make it much cleaner.

Here is a suggested refactoring that addresses both points by organizing the tests and placing them inside a __main__ guard:

if __name__ == "__main__":
    # Sample input
    original = [6, 6, 2, 3, 2]

    print("Original list:")
    print(original)

    # Sorting functions to test: (name, function, is_in_place)
    sorting_algorithms = [
        ("Bubble Sort", bubble_sort, True),
        ("Selection Sort", selection_sort, True),
        ("Insertion Sort", insertion_sort, True),
        ("Merge Sort", merge_sort, False),
        ("Python .sort()", lambda arr: arr.sort(), True),
        ("Python sorted()", sorted, False),
    ]

    for name, sort_func, is_in_place in sorting_algorithms:
        arr_copy = original.copy()
        print(f"\n{name} result:")
        if is_in_place:
            sort_func(arr_copy)
            print(arr_copy)
        else:
            sorted_arr = sort_func(arr_copy)
            print(sorted_arr)

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.

2 participants