Bucket Sort


In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form.

The complexity of the Bucket Sort Technique

  • Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.

  • Space Complexity: O(nk) for worst case

Input and Output

Input:
A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Output:
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79

Algorithm

bucketSort(array, size)

Input − An array of data, and the total number in the array

Output − The sorted Array

Begin
   for i := 0 to size-1 do
      insert array[i] into the bucket index (size * array[i])
   done

   for i := 0 to size-1 do
      sort bucket[i]
   done

   for i := 0 to size -1 do
      gather items of bucket[i] and put in array
   done
End

Example

#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++) { //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 n;
   cout << "Enter the number of elements: ";
   cin >> n;
   float arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   bucketSort(arr, n);

   cout << "Array after Sorting: ";
   display(arr, n);
}

Output

Enter the number of elements: 10
Enter elements:
0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79

Rishi Raj
Rishi Raj

I am a coder

Updated on: 15-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements