forked from argonautica/sorting-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBeadSort.java
70 lines (58 loc) · 1.83 KB
/
BeadSort.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
public class BeadSort {
public static void main(String[] args) {
BeadSort now=new BeadSort();
int[] arr = new int[(int)(Math.random() * 11) + 5];
for(int i = 0;i < arr.length; i++)
arr[i] = (int)(Math.random() * 10);
System.out.print("Unsorted: ");
now.display1D(arr);
int[] sort = now.beadSort(arr);
System.out.print("Sorted: ");
now.display1D(sort);
}
int[] beadSort(int[] arr) {
int max = arr[0];
for(int i = 1; i < arr.length; i++)
if(arr[i] > max)
max = arr[i];
char[][] grid = new char[arr.length][max];
int[] levelcount = new int[max];
for(int i = 0; i < max; i++) {
levelcount[i] = 0;
for(int j = 0; j < arr.length; j++)
grid[j][i] = '_';
}
for(int i = 0; i < arr.length; i++) {
int num = arr[i];
for(int j = 0; num > 0; j++) {
grid[levelcount[j]++][j] = '*';
num--;
}
}
System.out.println();
display2D(grid);
int[] sorted = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
int putt = 0;
for(int j = 0; j < max && grid[arr.length-1-i][j] == '*'; j++)
putt++;
sorted[i] = putt;
}
return sorted;
}
void display1D(int[] arr) {
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
void display1D(char[] arr) {
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
void display2D(char[][] arr) {
for(int i = 0; i < arr.length; i++)
display1D(arr[i]);
System.out.println();
}
}