Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Bucket Sort To Sort an Array with Negative Numbers
Next article icon

Bucket Sort To Sort an Array with Negative Numbers

Last Updated : 31 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

We have discussed bucket sort in the main post on Bucket Sort . 
Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. In the above post, we have discussed Bucket Sort to sort numbers which are greater than zero. 
How to modify Bucket Sort to sort both positive and negative numbers? 
Example: 

Input : arr[] = { -0.897, 0.565, 0.656, -0.1234, 0, 0.3434 }  Output : -0.897 -0.1234  0 0.3434 0.565 0.656   

Here we considering number is in range -1.0 to 1.0 (floating point number) 
Algorithm : 

sortMixed(arr[], n) 1) Split array into two parts     create two Empty vector Neg[], Pos[]     (for negative and positive element respectively)    Store all negative element in Neg[] by converting    into positive (Neg[i] = -1 * Arr[i] )    Store all +ve in pos[]  (pos[i] =  Arr[i]) 2) Call function bucketSortPositive(Pos, pos.size())    Call function bucketSortPositive(Neg, Neg.size())  bucketSortPositive(arr[], n) 3) Create n empty buckets (Or lists). 4) Do following for every array element arr[i].         a) Insert arr[i] into bucket[n*array[i]] 5) Sort individual buckets using insertion sort. 6) Concatenate all sorted buckets. 


Below is implementation of above idea (for floating point number )
 

CPP
// C++ program to sort an array of positive // and negative numbers using bucket sort #include <bits/stdc++.h> using namespace std;  // Function to sort arr[] of size n using // bucket sort void bucketSort(vector<float> &arr, int n) {     // 1) Create n empty buckets     vector<float> b[n];      // 2) Put array elements in different     //    buckets     for (int i=0; i<n; i++)     {         int bi = n*arr[i]; // Index in bucket         b[bi].push_back(arr[i]);     }      // 3) Sort individual buckets     for (int i=0; i<n; i++)         sort(b[i].begin(), b[i].end());      // 4) Concatenate all buckets into arr[]     int index = 0;     arr.clear();     for (int i = 0; i < n; i++)         for (int j = 0; j < b[i].size(); j++)             arr.push_back(b[i][j]); }  // This function mainly splits array into two // and then calls bucketSort() for two arrays. void sortMixed(float arr[], int n) {     vector<float>Neg ;     vector<float>Pos;      // traverse array elements     for (int i=0; i<n; i++)     {         if (arr[i] < 0)              // store -Ve elements by             // converting into +ve element             Neg.push_back (-1 * arr[i]) ;         else             // store +ve elements             Pos.push_back (arr[i]) ;     }      bucketSort(Neg, (int)Neg.size());     bucketSort(Pos, (int)Pos.size());      // First store elements of Neg[] array     // by converting into -ve     for (int i=0; i < Neg.size(); i++)         arr[i] = -1 * Neg[ Neg.size() -1 - i];      // store +ve element     for(int j=Neg.size(); j < n; j++)         arr[j] = Pos[j - Neg.size()]; }  /* Driver program to test above function */ int main() {     float arr[] = {-0.897, 0.565, 0.656,                    -0.1234, 0, 0.3434};     int n = sizeof(arr)/sizeof(arr[0]);     sortMixed(arr, n);      cout << "Sorted array is \n";     for (int i=0; i<n; i++)         cout << arr[i] << " ";     return 0; } 
Java
// Java program to sort an array of positive  // and negative numbers using bucket sort  import java.util.*; class GFG {     // Function to sort arr[] of size n using    // bucket sort    static void bucketSort(Vector<Double> arr, int n)    {       // 1) Create n empty buckets      @SuppressWarnings("unchecked")     Vector<Double> b[] = new Vector[n];      for (int i = 0; i < b.length; i++)       b[i] = new Vector<Double>();      // 2) Put array elements in different      // buckets      for (int i = 0; i < n; i++)      {        int bi = (int)(n*arr.get(i)); // Index in bucket        b[bi].add(arr.get(i));      }       // 3) Sort individual buckets      for (int i = 0; i < n; i++)        Collections.sort(b[i]);       // 4) Concatenate all buckets into arr[]      int index = 0;      arr.clear();      for (int i = 0; i < n; i++)        for (int j = 0; j < b[i].size(); j++)          arr.add(b[i].get(j));    }     // This function mainly splits array into two    // and then calls bucketSort() for two arrays.    static void sortMixed(double arr[], int n)    {      Vector<Double>Neg = new Vector<>();      Vector<Double>Pos = new Vector<>();        // traverse array elements      for (int i = 0; i < n; i++)      {        if (arr[i] < 0)           // store -Ve elements by          // converting into +ve element          Neg.add (-1 * arr[i]) ;        else          // store +ve elements          Pos.add (arr[i]) ;      }      bucketSort(Neg, (int)Neg.size());      bucketSort(Pos, (int)Pos.size());       // First store elements of Neg[] array      // by converting into -ve      for (int i = 0; i < Neg.size(); i++)        arr[i] = -1 * Neg.get( Neg.size() -1 - i);       // store +ve element      for(int j = Neg.size(); j < n; j++)        arr[j] = Pos.get(j - Neg.size());    }     /* Driver program to test above function */   public static void main(String[] args)    {      double arr[] = {-0.897, 0.565, 0.656,                      -0.1234, 0, 0.3434};      int n = arr.length;      sortMixed(arr, n);       System.out.print("Sorted array is \n");      for (int i = 0; i < n; i++)        System.out.print(arr[i] + " ");    } }   // This code is contributed by Rajput-Ji  
Python3
# Python3 program to sort an array of positive # and negative numbers using bucket sort  # Function to sort arr[] of size n using # bucket sort def bucketSort(arr, n):          # 1) Create n empty buckets     b = []     for i in range(n):         b.append([])              # 2) Put array elements in different     #    buckets     for i in range(n):         bi = int(n*arr[i])         b[bi].append(arr[i])          # 3) Sort individual buckets     for i in range(n):         b[i].sort()              # 4) Concatenate all buckets into arr[]     index = 0     arr.clear()     for i in range(n):         for j in range(len(b[i])):             arr.append(b[i][j])  # This function mainly splits array into two # and then calls bucketSort() for two arrays. def sortMixed(arr, n):     Neg = []     Pos = []          # traverse array elements     for i in range(n):         if(arr[i]<0):             # store -Ve elements by             # converting into +ve element             Neg.append(-1*arr[i])         else:             # store +ve elements             Pos.append(arr[i])                  bucketSort(Neg,len(Neg))     bucketSort(Pos,len(Pos))          # First store elements of Neg[] array     # by converting into -ve     for i in range(len(Neg)):         arr[i]=-1*Neg[len(Neg)-1-i]              # store +ve element     for i in range(len(Neg),n):         arr[i]= Pos[i-len(Neg)]  # Driver program to test above function arr = [-0.897, 0.565, 0.656, -0.1234, 0, 0.3434] sortMixed(arr, len(arr)) print("Sorted Array is") print(arr)  # This code is contributed by Pushpesh raj 
C#
// C# program to sort an array of positive  // and negative numbers using bucket sort  using System; using System.Collections.Generic;  public class GFG {     // Function to sort []arr of size n using    // bucket sort    static void bucketSort(List<Double> arr, int n)    {       // 1) Create n empty buckets       List<Double> []b = new List<Double>[n];      for (int i = 0; i < b.Length; i++)       b[i] = new List<Double>();      // 2) Put array elements in different      // buckets      for (int i = 0; i < n; i++)      {        int bi = (int)(n*arr[i]); // Index in bucket        b[bi].Add(arr[i]);      }       // 3) Sort individual buckets      for (int i = 0; i < n; i++)        b[i].Sort();      // 4) Concatenate all buckets into []arr      int index = 0;      arr.Clear();      for (int i = 0; i < n; i++)        for (int j = 0; j < b[i].Count; j++)          arr.Add(b[i][j]);    }     // This function mainly splits array into two    // and then calls bucketSort() for two arrays.    static void sortMixed(double []arr, int n)    {      List<Double>Neg = new List<Double>();      List<Double>Pos = new List<Double>();        // traverse array elements      for (int i = 0; i < n; i++)      {        if (arr[i] < 0)           // store -Ve elements by          // converting into +ve element          Neg.Add (-1 * arr[i]) ;        else          // store +ve elements          Pos.Add (arr[i]) ;      }      bucketSort(Neg, (int)Neg.Count);      bucketSort(Pos, (int)Pos.Count);       // First store elements of Neg[] array      // by converting into -ve      for (int i = 0; i < Neg.Count; i++)        arr[i] = -1 * Neg[ Neg.Count -1 - i];       // store +ve element      for(int j = Neg.Count; j < n; j++)        arr[j] = Pos[j - Neg.Count];    }     /* Driver program to test above function */   public static void Main(String[] args)    {      double []arr = {-0.897, 0.565, 0.656,                      -0.1234, 0, 0.3434};      int n = arr.Length;      sortMixed(arr, n);       Console.Write("Sorted array is \n");      for (int i = 0; i < n; i++)        Console.Write(arr[i] + " ");    } }   // This code is contributed by Rajput-Ji 
JavaScript
function bucketSort(arr, n) {   // 1) Create n empty buckets   var b = new Array(n);   for (var i = 0; i < n; i++) {     b[i] = [];   }    // 2) Put array elements in different buckets   for (var i = 0; i < n; i++) {     var bi = Math.floor(n * arr[i]); // Index in bucket     b[bi].push(arr[i]);   }    // 3) Sort individual buckets   for (var i = 0; i < n; i++) {     b[i].sort();   }    // 4) Concatenate all buckets into arr[]   var index = 0;   arr.length = 0;   for (var i = 0; i < n; i++) {     for (var j = 0; j < b[i].length; j++) {       arr.push(b[i][j]);     }   } }  // This function mainly splits array into two // and then calls bucketSort() for two arrays. function sortMixed(arr, n) {   var Neg = [];   var Pos = [];    // traverse array elements   for (var i = 0; i < n; i++) {     if (arr[i] < 0) {       // store -Ve elements by converting into +ve element       Neg.push(-1 * arr[i]);     } else {       // store +ve elements       Pos.push(arr[i]);     }   }    bucketSort(Neg, Neg.length);   bucketSort(Pos, Pos.length);    // First store elements of Neg[] array   // by converting into -ve   for (var i = 0; i < Neg.length; i++) {     arr[i] = -1 * Neg[Neg.length - 1 - i];   }    // store +ve element   for (var j = Neg.length; j < n; j++) {     arr[j] = Pos[j - Neg.length];   } }  /* Driver program to test above function */ (function main() {   var arr = [-0.897, 0.565, 0.656, -0.1234, 0, 0.3434];   var n = arr.length;   sortMixed(arr, n);    console.log("Sorted array is");   for (var i = 0; i < n; i++) {     console.log(arr[i] + " ");   } })(); 

Output
Sorted array is  -0.897 -0.1234 0 0.3434 0.565 0.656 

 


Next Article
Bucket Sort To Sort an Array with Negative Numbers

K

kartik
Improve
Article Tags :
  • Sorting
  • DSA
Practice Tags :
  • Sorting

Similar Reads

    Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
    Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read

    Most Common Sorting Algorithms

    Selection Sort
    Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
    8 min read
    Bubble Sort Algorithm
    Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
    8 min read
    Insertion Sort Algorithm
    Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
    9 min read
    Merge Sort - Data Structure and Algorithms Tutorials
    Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
    14 min read
    Quick Sort
    QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
    12 min read
    Heap Sort - Data Structures and Algorithms Tutorials
    Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
    14 min read
    Counting Sort - Data Structures and Algorithms Tutorials
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    9 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