-
-
Notifications
You must be signed in to change notification settings - Fork 410
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
Improved Bubble Sort Algorithm #215
base: master
Are you sure you want to change the base?
Conversation
Quality Gate passedIssues Measures |
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good initiative. Please check the code formatting. Checkstyle tests are failing.
|
||
} while (!sorted); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add empty line at EOF to satisfy github
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
Proposal: This new code improves the performance of the Bubble Sort Algorithm by a significant margin.
Problem: The earlier version of the Bubble Sort Code Snippet was taking a best case scenario of O(n^2) because the case where the array is already sorted was not being considered.
Improvements: The improved version of the code does the following things,
Correct Loop Structure: The nested loop structure has been revised to ensure proper sorting. The outer loop now uses a do-while construct, which iterates until the array is confirmed to be sorted thus reducing the time complexity if the array is already sorted. The inner loop handles the comparison and swapping of adjacent elements.
Early Termination: The implementation includes a sorted flag to allow the algorithm to terminate early if no swaps are made during a pass, indicating the array is already sorted. This optimization improves the best-case performance to O(n).
Reduced Range After Each Pass: The lastIndex variable is decremented after each pass to reduce the range of comparisons in subsequent iterations, as the largest elements bubble up to their correct positions.
Request: I would like to request to implement the proposed solution in the bubbleSort() function.