Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
B+ Tree in Python
Next article icon

Bucket Sort - Python

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Bucket sort is a sorting technique that involves dividing elements into various groups, or buckets. These buckets are formed by uniformly distributing the elements. Once the elements are divided into buckets, they can be sorted using any other sorting algorithm. Finally, the sorted elements are gathered together in an ordered fashion.

Bucket Sort Algorithm

  • Create an array of empty buckets.
  • Iterate through the input array and distribute each element into the corresponding bucket based on some criteria.
  • Sort each bucket individually (using another sorting algorithm or recursively applying bucket sort).
  • Concatenate all the sorted buckets to get the final sorted array.

How does Bucket Sort work?

To apply bucket sort on the input array [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68], we follow these steps:

Step 1: Create an array of size 10, where each slot represents a bucket.

Step 2: Insert elements into the buckets from the input array based on their range (For multiple elements on same bucket, Linked List Data Structure will be used).

Inserting elements into the buckets:

  • Take each element from the input array.
  • Multiply the element by the size of the bucket array (10 in this case). For example, for element 0.23, we get 0.23 * 10 = 2.3.
  • Convert the result to an integer, which gives us the bucket index. In this case, 2.3 is converted to the integer 2.
  • Insert the element into the bucket corresponding to the calculated index.
  • Repeat these steps for all elements in the input array.

Step 3: Sort the elements within each bucket. In this example, we use quicksort (or any stable sorting algorithm) to sort the elements within each bucket (Each bucket is treated a different Linked List and sorted in ascending order).

Sorting the elements within each bucket:

  • Apply a stable sorting algorithm (e.g., Bubble Sort, Merge Sort) to sort the elements within each bucket.
  • The elements within each bucket are now sorted.

Step 4: Gather the elements from each bucket and put them back into the original array.

Gathering elements from each bucket:

  • Iterate through each bucket in order.
  • Insert each individual element from the bucket into the original array.
  • Once an element is copied, it is removed from the bucket.
  • Repeat this process for all buckets until all elements have been gathered.

Step 5: The original array now contains the sorted elements.

The final sorted array using bucket sort for the given input is [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94].

Implementation of Bucket Sort in Python

Below is the implementation of bucket sort in python:

Python
def insertion_sort(bucket):     for i in range(1, len(bucket)):         key = bucket[i]         j = i - 1         while j >= 0 and bucket[j] > key:             bucket[j + 1] = bucket[j]             j -= 1         bucket[j + 1] = key  def bucket_sort(arr):     n = len(arr)     buckets = [[] for _ in range(n)]      # Put array elements in different buckets     for num in arr:         bi = int(n * num)         buckets[bi].append(num)      # Sort individual buckets using insertion sort     for bucket in buckets:         insertion_sort(bucket)      # Concatenate all buckets into arr[]     index = 0     for bucket in buckets:         for num in bucket:             arr[index] = num             index += 1  arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] bucket_sort(arr) print("Sorted array is:") print(" ".join(map(str, arr))) 

Output
Sorted array is: 0.12 0.17 0.21 0.23 0.26 0.39 0.68 0.72 0.78 0.94 

Complexity Analysis of Bucket Sort Algorithm

Time Complexity: O(n2),

  • If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time.
  • The O(1) is easily possible if we use a linked list to represent a bucket.
  • Step 4 also takes O(n) time as there will be n items in all buckets. 
  • The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed.

Auxiliary Space: O(n+k)


Next Article
B+ Tree in Python

C

code_r
Improve
Article Tags :
  • DSA
  • Python-DSA

Similar Reads

  • How To Store Data in a S3 Bucket?
    Pre-requisite: S3 (Simple Storage Service) AWS S3(Simple Storage Service) is a storage-as-a-service platform provided by Amazon. S3 offers various types of storage classes such as Standard, Standard IA, Intelligent, Reduced Redundancy, and Glacier. Amazon S3 stores the data inside a bucket in the fo
    3 min read
  • Stack in Python
    A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. The functions associated wi
    8 min read
  • Radix Sort vs Bucket Sort
    We have two standard sorting algorithms, named bucket sort and radix sort. They both share differences and similarities. Let’s explore some similarities, differences, advantages, and disadvantages here in more detail. Bucket Sort: Bucket sort is a sorting algorithm in which the elements are separate
    6 min read
  • Bucket Sort vs Quick Sort
    Bucket Sort and Quick Sort are two different sorting algorithms, each with its own characteristics, advantages, and disadvantages. In this article, we will provide a detailed overview of all the differences between Bucket Sort and Quick Sort. Bucket Sort:Bucket Sort is a non-comparison sorting algor
    3 min read
  • B+ Tree in Python
    In computer science, data structures are crucial in efficiently managing and organizing data. Among these, the B+ tree is a powerful and important data structure, widely used in databases and file systems. In this article, we will discuss the concept of B+ trees, exploring their structure, operation
    12 min read
  • B Tree in Python
    A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. Table of Content Characteristics of B-TreesTraversal of B-Tree in PythonSearch operation in B Tree in PythonInsert operation in B Tree in
    14 min read
  • Python Shelve Module
    In this article, we will learn to create a shelf file, store data in a shelf file, retrieve the data that is stored in the shelf file, update the data of a shelf file, get a list of shelf keys, Delete data stored in a shelf file and closing shelf file. The Shelve module is used to store data when us
    6 min read
  • Tag sort or Bucket sort or Bin sort in Python
    Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in
    2 min read
  • Best way to learn python
    Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time.
    11 min read
  • Count-Min Sketch in Python
    Count-Min Sketch is a probabilistic data structure which approximates the frequency of items in a stream of data. It uses little memory while handling massive amounts of data and producing approximations of the answers. In this post, we'll explore the idea behind the Count-Min Sketch, how it's imple
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences