Skip to content

Commit 4990f79

Browse files
authored
Add Bead Sort (TheAlgorithms#3761)
1 parent b8d6b1a commit 4990f79

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.sorts;
2+
3+
4+
//BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort
5+
//BeadSort can't sort negative number, Character, String. It can sort positive number only
6+
7+
public class BeadSort {
8+
public int[] sort(int[] unsorted) {
9+
int[] sorted = new int[unsorted.length];
10+
int max = 0;
11+
for(int i = 0; i < unsorted.length; i++) {
12+
max = Math.max(max, unsorted[i]);
13+
}
14+
15+
char[][] grid = new char[unsorted.length][max];
16+
int[] count = new int[max];
17+
18+
for(int i = 0; i < unsorted.length; i++) {
19+
for(int j = 0; j < max; j++) {
20+
grid[i][j] = '-';
21+
}
22+
}
23+
24+
for(int i = 0; i < max; i++) {
25+
count[i] = 0;
26+
}
27+
28+
for(int i = 0; i < unsorted.length; i++) {
29+
int k = 0;
30+
for(int j = 0; j < (int) unsorted[i] ; j++) {
31+
grid[count[max - k - 1]++][k] = '*';
32+
k++;
33+
}
34+
}
35+
36+
for(int i = 0; i < unsorted.length; i++) {
37+
int k = 0;
38+
for(int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) {
39+
k++;
40+
}
41+
sorted[i] = k;
42+
}
43+
return sorted;
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.thealgorithms.sorts;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class BeadSortTest {
8+
//BeadSort can't sort negative number, Character, String. It can sort positive number only
9+
private BeadSort beadSort = new BeadSort();
10+
11+
@Test
12+
public void beadSortEmptyArray() {
13+
int[] inputArray = {};
14+
int[] outputArray = beadSort.sort(inputArray);
15+
int[] expectedOutput = {};
16+
assertArrayEquals(outputArray, expectedOutput);
17+
}
18+
19+
@Test
20+
public void beadSortSingleIntegerArray() {
21+
int[] inputArray = { 4 };
22+
int[] outputArray = beadSort.sort(inputArray);
23+
int[] expectedOutput = { 4 };
24+
assertArrayEquals(outputArray, expectedOutput);
25+
}
26+
27+
@Test
28+
public void bogoSortNonDuplicateIntegerArray() {
29+
int[] inputArray = { 6, 1, 99, 27, 15, 23, 36 };
30+
int[] outputArray = beadSort.sort(inputArray);
31+
int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99};
32+
assertArrayEquals(outputArray, expectedOutput);
33+
}
34+
35+
@Test
36+
public void bogoSortDuplicateIntegerArray() {
37+
int[] inputArray = { 6, 1, 27, 15, 23, 27, 36, 23 };
38+
int[] outputArray = beadSort.sort(inputArray);
39+
int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36};
40+
assertArrayEquals(outputArray, expectedOutput);
41+
}
42+
}

0 commit comments

Comments
 (0)