File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Java program to sort an array using bucket sort
2
+ import java .util .*;
3
+ import java .util .Collections ;
4
+
5
+ class GFG {
6
+
7
+ // Function to sort arr[] of size n using bucket sort
8
+ static void bucketSort (float arr [], int n )
9
+ {
10
+ if (n <= 0 )
11
+ return ;
12
+
13
+ @ SuppressWarnings ("unchecked" )
14
+ Vector <Float >[] buckets = new Vector [n ];
15
+
16
+ for (int i = 0 ; i < n ; i ++) {
17
+ buckets [i ] = new Vector <Float >();
18
+ }
19
+
20
+
21
+ for (int i = 0 ; i < n ; i ++) {
22
+ float idx = arr [i ] * n ;
23
+ buckets [(int )idx ].add (arr [i ]);
24
+ }
25
+
26
+
27
+ for (int i = 0 ; i < n ; i ++) {
28
+ Collections .sort (buckets [i ]);
29
+ }
30
+
31
+
32
+ int index = 0 ;
33
+ for (int i = 0 ; i < n ; i ++) {
34
+ for (int j = 0 ; j < buckets [i ].size (); j ++) {
35
+ arr [index ++] = buckets [i ].get (j );
36
+ }
37
+ }
38
+ }
39
+
40
+ // Driver code
41
+ public static void main (String args [])
42
+ {
43
+ float arr [] = { (float )0.897 , (float )0.565 ,
44
+ (float )0.656 , (float )0.1234 ,
45
+ (float )0.665 , (float )0.3434 };
46
+
47
+ int n = arr .length ;
48
+ bucketSort (arr , n );
49
+
50
+ System .out .println ("Sorted array is " );
51
+ for (float el : arr ) {
52
+ System .out .print (el + " " );
53
+ }
54
+ }
55
+ }
56
+
Original file line number Diff line number Diff line change
1
+ // Java Program to implement Gnome Sort
2
+
3
+ import java .util .Arrays ;
4
+ public class GFG {
5
+ static void gnomeSort (int arr [], int n )
6
+ {
7
+ int index = 0 ;
8
+
9
+ while (index < n ) {
10
+ if (index == 0 )
11
+ index ++;
12
+ if (arr [index ] >= arr [index - 1 ])
13
+ index ++;
14
+ else {
15
+ int temp = 0 ;
16
+ temp = arr [index ];
17
+ arr [index ] = arr [index - 1 ];
18
+ arr [index - 1 ] = temp ;
19
+ index --;
20
+ }
21
+ }
22
+ return ;
23
+ }
24
+
25
+ // Driver program to test above functions.
26
+ public static void main (String [] args )
27
+ {
28
+ int arr [] = { 34 , 2 , 10 , -9 };
29
+
30
+ gnomeSort (arr , arr .length );
31
+
32
+ System .out .print ("Sorted sequence after applying Gnome sort: " );
33
+ System .out .println (Arrays .toString (arr ));
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments