Skip to content

Commit 7175c39

Browse files
authored
Merge pull request #478 from kiki2601/master
adding bucket sort
2 parents 6a90742 + 049d10f commit 7175c39

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

java/sorting/Bucket_Sort.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+

java/sorting/Gnome_sort.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)