forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBeadSort.java
More file actions
44 lines (37 loc) · 1.23 KB
/
BeadSort.java
File metadata and controls
44 lines (37 loc) · 1.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
package com.thealgorithms.sorts;
// BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort
// BeadSort can't sort negative number, Character, String. It can sort positive number only
public class BeadSort {
public int[] sort(int[] unsorted) {
int[] sorted = new int[unsorted.length];
int max = 0;
for (int i = 0; i < unsorted.length; i++) {
max = Math.max(max, unsorted[i]);
}
char[][] grid = new char[unsorted.length][max];
int[] count = new int[max];
for (int i = 0; i < unsorted.length; i++) {
for (int j = 0; j < max; j++) {
grid[i][j] = '-';
}
}
for (int i = 0; i < max; i++) {
count[i] = 0;
}
for (int i = 0; i < unsorted.length; i++) {
int k = 0;
for (int j = 0; j < unsorted[i]; j++) {
grid[count[max - k - 1]++][k] = '*';
k++;
}
}
for (int i = 0; i < unsorted.length; i++) {
int k = 0;
for (int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) {
k++;
}
sorted[i] = k;
}
return sorted;
}
}