Bucket Sort To Sort an Array with Negative Numbers | Java 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 = ( int ) ( n * arr . get ( 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
import java . util . * ; class GFG { static void bucketSort ( Vector < Double > arr , int n ) { @ SuppressWarnings ( " unchecked " ) Vector < Double > b [ ] = new Vector [ n ] ; for ( int i = 0 ; i < b . length ; i ++ ) b [ i ] = new Vector < Double > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { b [ bi ] . add ( arr . get ( i ) ) ; } for ( int i = 0 ; i < n ; i ++ ) Collections . sort ( b [ i ] ) ; 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 ) ) ; } static void sortMixed ( double arr [ ] , int n ) { Vector < Double > Neg = new Vector < > ( ) ; Vector < Double > Pos = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) Neg . add ( - 1 * arr [ i ] ) ; else Pos . add ( arr [ i ] ) ; } bucketSort ( Neg , ( int ) Neg . size ( ) ) ; bucketSort ( Pos , ( int ) Pos . size ( ) ) ; for ( int i = 0 ; i < Neg . size ( ) ; i ++ ) arr [ i ] = - 1 * Neg . get ( Neg . size ( ) - 1 - i ) ; for ( int j = Neg . size ( ) ; j < n ; j ++ ) arr [ j ] = Pos . get ( j - Neg . size ( ) ) ; } 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 NEW_LINE"); for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }