-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Optimization shell sort #4119
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
Optimization shell sort #4119
Conversation
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.
It doesn't quite seem to me that this is an optimization. May I know the reasoning behind this?
If array is sorted already. It's no need to execute assignment statement. See this |
@shellhub I've done a simple benchmark for this on random and sorted lists. I'd say they're similar in performance... Can you illustrate with an example in the test & comment: like # consider test case [xxx] |
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.
@shellhub Please create a timeit (or similar) benchmark that proves that the proposed change delivers measurable performance improvement.
def shell_sort_slow(collection):
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(collection)):
insert_value = collection[i]
j = i
while j >= gap and collection[j - gap] > insert_value:
collection[j] = collection[j - gap]
j -= gap
collection[j] = insert_value
return collection
def shell_sort_faster(collection):
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(collection)):
insert_value = collection[i]
j = i
while j >= gap and collection[j - gap] > insert_value:
collection[j] = collection[j - gap]
j -= gap
if j != i:
collection[j] = insert_value
return collection
def benchmark():
from timeit import timeit
print("shell_sort_slow", timeit("z.shell_sort_slow(z.nums)", setup="import __main__ as z"))
print("shell_sort_faster", timeit("z.shell_sort_faster(z.nums)", setup="import __main__ as z"))
if __name__ == "__main__":
nums = [i for i in range(1, 1000)]
benchmark() output:
|
Please review this PR. Thanks @poyea @cclauss @dhruvmanila @mateuszz0000 |
* optimization * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
* optimization * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
* optimization * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Describe your change:
Checklist:
Fixes: #{$ISSUE_NO}
.