-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added bucket_sort.py & shell_sort.py (#296)
* Create bucket_sort.py * Create shell_sort.py * Update test_sort.py * Update __init__.py
- Loading branch information
1 parent
91aee95
commit b39f4e5
Showing
4 changed files
with
63 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
def bucket_sort(arr): | ||
''' Bucket Sort | ||
Complexity: O(n^2) | ||
The complexity is dominated by nextSort | ||
''' | ||
# The number of buckets and make buckets | ||
num_buckets = len(arr) | ||
buckets = [[] for bucket in range(num_buckets)] | ||
# Assign values into bucket_sort | ||
for value in arr: | ||
index = value * num_buckets // (max(arr) + 1) | ||
buckets[index].append(value) | ||
# Sort | ||
sorted_list = [] | ||
for i in range(num_buckets): | ||
sorted_list.extend(next_sort(buckets[i])) | ||
return sorted_list | ||
|
||
def next_sort(arr): | ||
# We will use insertion sort here. | ||
for i in range(1, len(arr)): | ||
j = i - 1 | ||
key = arr[i] | ||
while arr[j] > key and j >= 0: | ||
arr[j+1] = arr[j] | ||
j = j - 1 | ||
arr[j + 1] = key | ||
return arr |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
def shell_sort(arr): | ||
''' Shell Sort | ||
Complexity: O(n^2) | ||
''' | ||
n = len(arr) | ||
# Initialize size of the gap | ||
gap = n//2 | ||
|
||
while gap > 0: | ||
y_index = gap | ||
while y_index < len(arr): | ||
y = arr[y_index] | ||
x_index = y_index - gap | ||
while x_index >= 0 and y < arr[x_index]: | ||
arr[x_index + gap] = arr[x_index] | ||
x_index = x_index - gap | ||
arr[x_index + gap] = y | ||
y_index = y_index + 1 | ||
gap = gap//2 | ||
|
||
return arr |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters