-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBucketSort.java
More file actions
76 lines (54 loc) · 1.68 KB
/
BucketSort.java
File metadata and controls
76 lines (54 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.*;
public class BucketSort {
public static void main(String[] args) {
String[] myList = new String[args.length];
System.out.println("Unsorted List: ");
for (int i = 0; i < args.length; i++){
myList[i]= args[i];
System.out.printf(myList[i] + " ","/n");
}
System.out.println();
sort(myList);
System.out.println();
System.out.println("After Bucket Sort:");
System.out.println(Arrays.toString(myList));
}
public static void sort(String[] wordList) {
int index = 0;
int max = 0;
char a = 'a';
if (wordList.length == 0) return;
for (int i = 1; i < wordList.length; i++) {
if (max < wordList[i].length()) max = wordList[i].length();
}
int counter = 26;
HashMap<Character, Vector<String>> buckets = new HashMap<Character, Vector<String>>(counter);
for (int i = 0; i <= counter; i++, a++){
buckets.put(a, new Vector<String>());
}
System.out.println("Bucket size: " + counter);
System.out.println();
for (int i = 0; i < wordList.length; i++) {
String current = wordList[i];
char letter = current.toLowerCase().charAt(0);
buckets.get(letter).add(wordList[i]);
}
for (char letter = 'a'; letter <= 'z'; letter++) {
Vector<String> bucket = buckets.get(letter);
System.out.println("Bucket "+ letter+": "+bucket);
for (int i = 1; i < bucket.size(); i++){
String temp = bucket.get(i);
bucket.remove(i);
int j;
for(j = i-1; j >= 0 && bucket.get(j).compareToIgnoreCase(temp) > 0; j--){
bucket.add(j+1, bucket.get(j));
bucket.remove(j);
}
bucket.add(j+1, temp);
}
for (int k = 0; k < bucket.size(); k++) {
wordList[index++] = bucket.get(k);
}
}
}
}