forked from Soumyadeep-Sadhu/HacktoberFest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBucket_sort.cpp
77 lines (40 loc) · 1.12 KB
/
Bucket_sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void display(float *array, int size) {
for(int i = 0; i<size; i++)
cout<< array[i]<<" ";
cout<<endl;
}
void bucketSort(float *array, int size) {
vector<float> bucket[size];
for(int i = 0; i<size; i++) { //adding elements into different buckets
bucket[int(size*array[i])].push_back(array[i]);
}
for(int i = 0; i<size; i++) {
sort(bucket[i].begin(), bucket[i].end()); //sort individual buckets
}
int index = 0;
for(int i = 0; i<size; i++) {
while(!bucket[i].empty()) {
array[index++] = *(bucket[i].begin());
bucket[i].erase(bucket[i].begin());
}
}
}
int main() {
int n;
cout << "Enter the number of elements to be sorted: ";
cin >> n;
float arr[n]; //create an array with given number of elements
cout<<"Enter the elements:"<<endl;
for(int i = 0; i<n; i++) {
cin>>arr[i];
}
cout<<"\nARRAY BEFORE SORTING: ";
display(arr, n);
bucketSort(arr, n);
cout <<"\nARRAY AFTER SORTING USING BUCKET SORT: ";
display(arr, n);
}