- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathradix_sort.java
More file actions
Latest commit
65 lines (58 loc) · 2.23 KB
/
Copy pathradix_sort.java
File metadata and controls
65 lines (58 loc) · 2.23 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
importjava.util.Arrays;
importjava.util.Scanner;
publicclassradix_sort {
publicstaticvoidmain(String[] args) {
// import scanner to take user input
Scannersc = newScanner(System.in);
System.out.println("enter the size of the array");
intsize = sc.nextInt();
System.out.println("enter the element in the array");
int[] arr = newint[size];
// store the inputed elements in the array
for(inti = 0; i<size; i++) {
arr[i] = sc.nextInt();
}
// call our sorting function
radixSort(arr);
System.out.println(Arrays.toString(arr));
}
publicstaticvoidradixSort(int[] arr) {
// search for the maximum number to know the number of digits
intmax = getMax(arr);
// do counting sort here
for (intexp = 1; max/exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}
publicstaticvoidcountingSort(int[] arr, intexp) { // sort the array by each digit starting with the least significant digit in the array
int[] output = newint[arr.length]; // the final array in which we will store our answer
int[] count = newint[10]; // the counting array
// store all the counting occourences in count array
for (inti = 0; i < arr.length; i++) {
count[(arr[i]/exp)%10]++;
}
// change our element at count[i] to count[i-1] so that this contains actual position of the digit in output array
for (inti = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// create our output array
for (inti = arr.length - 1; i >= 0; i--) {
output[count[(arr[i]/exp)%10] - 1] = arr[i];
count[(arr[i]/exp)%10]--;
}
// store the output array in our ans array, so that numbers that are sorted now can be stored
for (inti = 0; i < arr.length; i++) {
arr[i] = output[i];
}
}
// normal function to find the max value in our array
publicstaticintgetMax(int[] arr) {
intmax = arr[0];
for (inti = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
returnmax;
}
}