0% found this document useful (0 votes)
4 views2 pages

Assignment7 - Bucket Sort (20058570055)

The document contains a C++ program that implements the Bucket Sort algorithm. It includes functions to display an array, sort the elements into buckets, and sort each bucket individually before merging them back into the original array. The program prompts the user to input the number of elements and the elements themselves, displaying the array before and after sorting.

Uploaded by

Richa Kothari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Assignment7 - Bucket Sort (20058570055)

The document contains a C++ program that implements the Bucket Sort algorithm. It includes functions to display an array, sort the elements into buckets, and sort each bucket individually before merging them back into the original array. The program prompts the user to input the number of elements and the elements themselves, displaying the array before and after sorting.

Uploaded by

Richa Kothari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Name: Richa Kothari

Roll no. : 20058570028

Ques: Write a program to implement Bucket sort.

Code:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void show(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++) { //put 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 vectors
}
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 element;
cout << "Enter the number of elements: ";
cin >> element;
float arr[element]; //create an array with given number of elements
cout << "\nEnter elements:" << endl;
for(int i = 0; i<element; i++) {
cin >> arr[i];
}
cout << "\nArray before Sorting: ";
show(arr, element);
bucketSort(arr, element);
cout << "\nArray after Sorting: ";
show(arr, element);
}
Output:

You might also like