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 = ( int ) ( 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
using System ; using System . Collections . Generic ; public class GFG { static void bucketSort ( List < Double > arr , int n ) { List < Double > [ ] b = new List < Double > [ n ] ; for ( int i = 0 ; i < b . Length ; i ++ ) b [ i ] = new List < Double > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { b [ bi ] . Add ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) b [ i ] . Sort ( ) ; 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 ] ) ; } static void sortMixed ( double [ ] arr , int n ) { List < Double > Neg = new List < Double > ( ) ; List < Double > Pos = new List < Double > ( ) ; 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 . Count ) ; bucketSort ( Pos , ( int ) Pos . Count ) ; for ( int i = 0 ; i < Neg . Count ; i ++ ) arr [ i ] = - 1 * Neg [ Neg . Count - 1 - i ] ; for ( int j = Neg . Count ; j < n ; j ++ ) arr [ j ] = Pos [ j - Neg . Count ] ; } 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 ▁ STRNEWLINE " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }