forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bead_Sort.java
101 lines (93 loc) · 2.36 KB
/
Bead_Sort.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
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=0;
for(int i=0;i<arr.length;i++)
if(arr[i]>max)
max=arr[i];
//Set up abacus
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]='_';
}
/*
display1D(arr);
display1D(levelcount);
display2D(grid);
*/
//Drop the beads
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);
//Count the beads
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();
}
}
// Unsorted: 9 4 7 0 4 3 0 5 3 8 7 9 8 7 0
// * * * * * * * * *
// * * * * * * * * *
// * * * * * * * * _
// * * * * * * * * _
// * * * * * * * _ _
// * * * * * * * _ _
// * * * * * * * _ _
// * * * * * _ _ _ _
// * * * * _ _ _ _ _
// * * * * _ _ _ _ _
// * * * _ _ _ _ _ _
// * * * _ _ _ _ _ _
// _ _ _ _ _ _ _ _ _
// _ _ _ _ _ _ _ _ _
// _ _ _ _ _ _ _ _ _
// Sorted: 0 0 0 3 3 4 4 5 7 7 7 8 8 9 9