Bucket Sort To Sort an Array with Negative Numbers | C ++ program to sort an array of positive and negative numbers using bucket sort ; Function to sort arr [ ] of size n using bucket sort ; 1 ) Create n empty buckets ; 2 ) Put array elements in different buckets ; int bi = n * arr [ i ] ; Index in bucket ; 3 ) Sort individual buckets ; 4 ) Concatenate all buckets into arr [ ] ; This function mainly splits array into two and then calls bucketSort ( ) for two arrays . ; traverse array elements ; store - Ve elements by converting into + ve element ; store + ve elements ; First store elements of Neg [ ] array by converting into - ve ; store + ve element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bucketSort ( vector < float > & arr , int n ) { vector < float > b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { b [ bi ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) sort ( b [ i ] . begin ( ) , b [ i ] . end ( ) ) ; 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 ] ) ; } void sortMixed ( float arr [ ] , int n ) { vector < float > Neg ; vector < float > Pos ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) Neg . push_back ( -1 * arr [ i ] ) ; else Pos . push_back ( arr [ i ] ) ; } bucketSort ( Neg , ( int ) Neg . size ( ) ) ; bucketSort ( Pos , ( int ) Pos . size ( ) ) ; for ( int i = 0 ; i < Neg . size ( ) ; i ++ ) arr [ i ] = -1 * Neg [ Neg . size ( ) - 1 - i ] ; for ( int j = Neg . size ( ) ; j < n ; j ++ ) arr [ j ] = Pos [ j - Neg . size ( ) ] ; } 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 ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }