-
Notifications
You must be signed in to change notification settings - Fork 0
/
RadixSort.java
78 lines (66 loc) · 1.95 KB
/
RadixSort.java
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
77
78
/***************************************
* RadixSort.java Author: Robert Walker
*
* Purpose: Radix Sort
*
**************************************/
import java.util.*;
import java.io.*;
public class RadixSort {
public static int[] holder;
public static int length;
public static AdvCSLL<Integer>[] buckets = new AdvCSLL[10];
public static void main(String[] args) throws FileNotFoundException {
Scanner fs = new Scanner(new File("src/radixInput.txt"));
while (fs.hasNextLine()) {
length = fs.nextInt();
int i = 0;
holder = new int[length];
for (int j = 0; j < length; j++) {
holder[i] = fs.nextInt();
i++;
}
System.out.print("Unsorted: ");
printInput();
populateLinkedLists();
radixSort();
System.out.println();
System.out.print("Sorted: ");
printInput();
System.out.println();
}
}
public static void populateLinkedLists() {
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new AdvCSLL<>();
}
}
@SuppressWarnings("unchecked")
public static void radixSort() {
String lengthChecker = Integer.toString(holder[0]);
int intLength = lengthChecker.length() - 1;
for (int i = intLength; i > 0; i--) { // Runs once for each digit in input
for (int j = 0; j < holder.length; j++) { // Iterates holder
String holderString = Integer.toString(holder[j]); // String for each int in holder
int endValue = Integer.parseInt(holderString.substring(i - 1, i)); // End Value to sort
// by
buckets[endValue].add(holder[j]); // Add to buckets
}
int x = 0;
for (int j = 0; j < buckets.length; j++) {
while (!buckets[j].isEmpty()) {
holder[x] = buckets[j].removeFirst();
x++;
}
}
}
}
public static void printInput() {
String result = "";
for (int i = 0; i < holder.length; i++) {
result = result + holder[i] + ", ";
}
String finalResult = result.substring(0, result.length() - 2); // Remove last comma
System.out.print(finalResult);
}
}