-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRadixSort.java
101 lines (93 loc) · 2.7 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/*
* @Author Prashant Ghimire
* This program will sort the names on the considering their first three letters only using Radix sort algorithm.
* It also keep tracks on the number of comparisons made during the sorting process
*/
public class RadixSort {
public static void main(String[]args) throws FileNotFoundException{
Linkedlist[] allNameLinkedList = new Linkedlist[26]; // create an array of LinkedList for 26 letters in alphabets
int count = 0;
// initialize all the elements in the array to new LinkedList
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
Scanner scan = new Scanner(new File("radixnames.txt"));
// Put the names in the file according to their third character into the corresponding LinkedLists
// For example, "Zachary" would go to to allNameLinkedList[2]
while(scan.hasNextLine())
{
String currentname = scan.nextLine();
for(int i = 0; i < 26; i++){
if(currentname.charAt(2) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
count++;
}
// copy sorted nodes to new LinkedList called container
Linkedlist container = new Linkedlist();
for (int i = 0; i < 26; i++) {
Node n = allNameLinkedList[i].front;
while(n != null){
container.addNodeToTheEndOfTheList(n.name);
n = n.next;
}
}
// empty all the elements of array
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
Node m = container.front;
while(m!=null)
{
String currentname = m.name;
for(int i = 0; i < 26; i++){
if(currentname.charAt(1) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
m = m.next;
count++;
}
container = new Linkedlist();
for (int i = 0; i < 26; i++) {
m = allNameLinkedList[i].front;
while(m!=null){
container.addNodeToTheEndOfTheList(m.name);
m = m.next;
}
}
for (int i = 0; i < allNameLinkedList.length; i++) {
allNameLinkedList[i] = new Linkedlist();
}
m = container.front;
while(m!=null)
{
String currentname = m.name;
for(int i = 0; i < 26; i++){
if(currentname.charAt(0) == (char)(i+97))
{
allNameLinkedList[i].addNodeToTheEndOfTheList(currentname);
}
}
m = m.next;
count++;
}
container = new Linkedlist();
for (int i = 0; i < 26; i++) {
m = allNameLinkedList[i].front;
while(m!=null){
System.out.println(m.name);
container.addNodeToTheEndOfTheList(m.name);
m = m.next;
}
}
scan.close();
System.out.println("The total number of comparisions was :"+count);
}
}