Skip to content

Commit 63b9e13

Browse files
authored
Create BucketSort.java
1 parent 0705384 commit 63b9e13

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Sorts/BucketSort.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
2+
import java.util.Random;
3+
4+
public class Bucket_Sort
5+
{
6+
static int[] sort(int[] sequence, int maxValue)
7+
{
8+
// Bucket Sort
9+
int[] Bucket = new int[maxValue + 1];
10+
int[] sorted_sequence = new int[sequence.length];
11+
12+
for (int i = 0; i < sequence.length; i++)
13+
Bucket[sequence[i]]++;
14+
15+
int outPos = 0;
16+
for (int i = 0; i < Bucket.length; i++)
17+
for (int j = 0; j < Bucket[i]; j++)
18+
sorted_sequence[outPos++] = i;
19+
20+
return sorted_sequence;
21+
}
22+
23+
static void printSequence(int[] sorted_sequence)
24+
{
25+
for (int i = 0; i < sorted_sequence.length; i++)
26+
System.out.print(sorted_sequence[i] + " ");
27+
}
28+
29+
static int maxValue(int[] sequence)
30+
{
31+
int maxValue = 0;
32+
for (int i = 0; i < sequence.length; i++)
33+
if (sequence[i] > maxValue)
34+
maxValue = sequence[i];
35+
return maxValue;
36+
}
37+
38+
public static void main(String args[])
39+
{
40+
System.out.println("Sorting of randomly generated numbers using BUCKET SORT");
41+
Random random = new Random();
42+
int N = 20;
43+
int[] sequence = new int[N];
44+
45+
for (int i = 0; i < N; i++)
46+
sequence[i] = Math.abs(random.nextInt(100));
47+
48+
int maxValue = maxValue(sequence);
49+
50+
System.out.println("\nOriginal Sequence: ");
51+
printSequence(sequence);
52+
53+
System.out.println("\nSorted Sequence: ");
54+
printSequence(sort(sequence, maxValue));
55+
}
56+
}
57+
58+
#Output:
59+
60+
$ javac Bucket_Sort.java
61+
$ java Bucket_Sort
62+
63+
Sorting of randomly generated numbers using BUCKET SORT
64+
65+
Original Sequence:
66+
95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66
67+
Sorted Sequence:
68+
8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy