Skip to content

Commit feabb75

Browse files
committed
Bucket Sort added
1 parent 693abae commit feabb75

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

Sorting Algorithms/bucket_sort.cpp

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets.
3+
Each bucket is then sorted individually, either using a different sorting algorithm,
4+
or by recursively applying the bucket sorting algorithm.Bucket sort is mainly useful when input is uniformly distributed
5+
over a range. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm.
6+
*/
7+
#include<bits/stdc++.h>
8+
using namespace std;
9+
10+
//to sort the individual bucket
11+
void Insertion_Sort(float arr[10][10], int n, int idx) {
12+
for (int i = 0; i < n; i++) {
13+
int k = i;
14+
float temp = arr[idx][i];
15+
while (k - 1 >= 0 && arr[idx][k] < arr[idx][k - 1]) {
16+
arr[idx][k] = arr[idx][k - 1];
17+
k = k - 1;
18+
}
19+
20+
arr[idx][k] = temp;
21+
}
22+
}
23+
24+
void Bucket_Sort(float arr[20], int n) {
25+
// Declare a 2D array of float numbers
26+
float temp[10][10];
27+
//count array stores the length of elements in the respective buckets
28+
int count[10] = {
29+
0
30+
};
31+
for (int i = 0; i < n; i++) {
32+
int idx = arr[i] * 10;
33+
temp[idx][count[idx]] = arr[i];
34+
count[idx]++;
35+
}
36+
37+
for (int i = 0; i < 10; i++) {
38+
if (count[i] > 0)
39+
Insertion_Sort(temp, count[i], i);
40+
}
41+
42+
//to rewrite the values in array in sorted order
43+
int i = 0;
44+
for (int j = 0; j < 10 && i < n; j++) {
45+
if (count[j] > 0) {
46+
for (int k = 0; k < count[j]; k++) {
47+
arr[i] = temp[j][k];
48+
i++;
49+
}
50+
}
51+
}
52+
}
53+
54+
int main() {
55+
// Declare a variable to store no. of elements
56+
int n;
57+
// Declare an array of float numbers
58+
float arr[20];
59+
cout << "Enter number of elements :\n";
60+
cin >> n;
61+
cout << "Enter the elements:\n";
62+
for (int i = 0; i < n; i++) {
63+
cin >> arr[i];
64+
}
65+
cout << "\n";
66+
Bucket_Sort(arr, n);
67+
cout << "\nSorted array is \n";
68+
//loop to print sorted array
69+
for (int i = 0; i < n; i++) {
70+
cout << "\t" << arr[i];
71+
}
72+
return 0;
73+
}
74+
75+
/*
76+
Input:
77+
Enter the number of elements :
78+
4
79+
Enter the elements:
80+
0.123 0.008 0.7 0.4
81+
Output:
82+
Sorted array is
83+
0.008 0.123 0.4 0.7
84+
85+
Time Complexities:
86+
O(n+k): average time complexity
87+
O(n²): worst time complexity
88+
Space Complexity: O(n+k)
89+
*/

0 commit comments

Comments
 (0)