Skip to content

Commit 143e355

Browse files
committed
bucket sort
1 parent e29cad9 commit 143e355

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Python implementation of Bucket Sort Algorithm
2+
3+
def bucketSort(array):
4+
bucket = []
5+
6+
# Create empty buckets
7+
for i in range(len(array)):
8+
bucket.append([])
9+
10+
# Insert elements into their respective buckets
11+
for j in array:
12+
index_b = int(10 * j)
13+
bucket[index_b].append(j)
14+
15+
# Sort the elements of each bucket
16+
for i in range(len(array)):
17+
bucket[i] = sorted(bucket[i])
18+
19+
# Get the sorted elements
20+
k = 0
21+
for i in range(len(array)):
22+
for j in range(len(bucket[i])):
23+
array[k] = bucket[i][j]
24+
k += 1
25+
return array
26+
27+
28+
array = [.42, .32, .33, .52, .37, .47, .51, .51]
29+
print("Sorted Array in descending order is")
30+
print(bucketSort(array))

README.md

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,7 @@
530530

531531
![](https://github.com/aish21/Algorithms-and-Data-Structures/blob/main/Resources/Animations/counting-sort.gif)
532532

533-
### [Radix Sort](/Practice%20Concepts/Sorting/counting-sort.py)
533+
### [Radix Sort](/Practice%20Concepts/Sorting/radix-sort.py)
534534
* Sorts the elements by first grouping the individual digits of the same place value. Then, sort the elements according to their increasing/decreasing order.
535535
* Method:
536536
- Find the largest element in the array
@@ -541,6 +541,22 @@
541541

542542
![](https://github.com/aish21/Algorithms-and-Data-Structures/blob/main/Resources/Animations/radix-sort.gif)
543543

544+
### [Bucket Sort](/Practice%20Concepts/Sorting/bucket-sort.py)
545+
* Sorting algorithm that divides the unsorted array elements into several groups (buckets)
546+
* Each bucket is then sorted by using any of the suitable sorting algorithms or recursively applying the same bucket algorithm
547+
* Method:
548+
- Create an array of size n. Each slot of this array is used as a bucket for storing elements.
549+
- Insert elements into the buckets from the array. The elements are inserted according to the range of the bucket.
550+
- The elements of each bucket are sorted using any of the stable sorting algorithms
551+
- The elements from each bucket are gathered
552+
* Time Complexity:
553+
- Best: O(n + k)
554+
- Average: O(n)
555+
- Worst: O(n<sup>2</sup>)
556+
* Space Complexity - O(n + k)
557+
558+
![](https://github.com/aish21/Algorithms-and-Data-Structures/blob/main/Resources/Animations/bucket.webp)
559+
544560
## Search Algorithms
545561
<p align="center">
546562
<a href="#linear-search">Linear Search</a> •

Resources/Animations/bucket.webp

99.5 KB
Loading

0 commit comments

Comments
 (0)