×

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally, we take the elements out and join them to get the sorted result.

The bucket sort assumes that the input is generated by a random process that distributes the elements uniformly over the interval (0,1).

The idea of ??bucket sort is to divide the interval 0 to 1 into “n” equal-sized sub-intervals or buckets, and then distribute the n input number to the bucket.

The bucket sort program requires an auxiliary array X [0, 1, 2, ...., n-1] of the linked list.

Complexity table of bucket sort

ComplexityBest caseAverage caseWorst case
TimeO(n + k)O(n + k)O(n2)
Space  O(n)

Algorithm of bucket sort

Bucket Sort() 
Step 1: Create N buckets and each buckets is hold a range of values. 
Step 2: for i ? 1 to n     // initialize each bucket with 0 values. 
Step 3: for i ? 1 to n     put elements into buckets matching the range. 
Step 4: for i ? 1 to n     sort elements in each bucket.     gather elements from each bucket 
Step 5: exit

For example: Suppose we have the following array, which we have to sort.

11861252

Step 1: Create a new array, and this array size is 10. Every field of this array is used as a bucket.  

Step 2: Insert the array element into the new array bucket, and these elements will be added according to the range of the bucket.    

Step 3: Gather the element form each bucket.  

Bucket sort program in C language:

#include <stdio.h> 
 void Bucket_Sort(int array[], int n) 
 {       
 int i, j;    
    int count[n];   
    for (i = 0; i < n; i++)     
      count[i] = 0;       
 for (i = 0; i < n; i++)   
       (count[array[i]])++;   
      for (i = 0, j = 0; i < n; i++)   
         for(; count[i] > 0; (count[i])--)  
            array[j++] = i;   
} 
      int main() 
 {    
  int array[100], i, num;  
        printf("Enter the size of array : ");   
      scanf("%d", &num);  
       printf("Enter the %d elements to be sorted:\n",num); 
      for (i = 0; i < num; i++)  
        scanf("%d", &array[i]);  
     printf("\nThe array of elements before sorting : \n");  
    for (i = 0; i < num; i++)  
        printf("%d ", array[i]);  
      printf("\nThe array of elements after sorting : \n");  
     Bucket_Sort(array, num);   
    for (i = 0; i < num; i++)  
        printf("%d ", array[i]);   
      printf("\n");        
   return 0; 
 } 

Bucket sort program in java language:

import java.util.ArrayList; 
import java.util.Collections;  
 public class BucketSort 
{  
 public void bucketSort(float[] arr, int n)
 {     
if (n <= 0)       return;  
   @SuppressWarnings("unchecked")   
  ArrayList<Float>[] bucket = new ArrayList[n];       // Create empty buckets   
  for (int i = 0; i < n; i++)   
    bucket[i] = new ArrayList<Float>();       // Add elements into the buckets     
for (int i = 0; i < n; i++)
 {     
  int bucketIndex = (int) arr[i] * n;  
     bucket[bucketIndex].add(arr[i]);  
   }  
     // Sort the elements of each bucket     for (int i = 0; i < n; i++) 
{    
   Collections.sort((bucket[i]));   
  }    
   // Get the sorted array     int index = 0;    
 for (int i = 0; i < n; i++) 
{   
    for (int j = 0, size = bucket[i].size(); j < size; j++) 
{      
   arr[index++] = bucket[i].get(j); 
      }    
 }  
 }  
   // Driver code   public static void main(String[] args) 
{   
  BucketSort b = new BucketSort();   
  float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47,         (float) 0.51 };   
  b.bucketSort(arr, 7); 
      for (float i : arr)       System.out.print(i + "  "); 
  } 
}

Related Topics

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 minutes read.

Introduction and Implementation of Bloom Filter

It often happens with many of us that when we create an account on some applications like Github, it shows us that the username already exists. You can add some...

4 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

4 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.