Skip to content

Commit bda656e

Browse files
committed
Add SleepSort algorithm
- Implements Sleep Sort using thread-based timing approach - Uses CountDownLatch for thread synchronization - Includes basic test suite for functionality verification
1 parent 9484c7e commit bda656e

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.concurrent.CountDownLatch;
4+
import java.util.concurrent.atomic.AtomicInteger;
5+
6+
/**
7+
* Sleep Sort Algorithm Implementation
8+
*
9+
* @see <a href="https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort">Sleep Sort Algorithm</a>
10+
*/
11+
public final class SleepSort {
12+
13+
private SleepSort() {
14+
}
15+
16+
public static int[] sort(int[] array) {
17+
if (array == null || array.length == 0) {
18+
return array;
19+
}
20+
21+
int[] result = new int[array.length];
22+
CountDownLatch latch = new CountDownLatch(array.length);
23+
AtomicInteger index = new AtomicInteger(0);
24+
25+
for (int value : array) {
26+
new Thread(() -> {
27+
try {
28+
Thread.sleep(Math.abs(value) + 1);
29+
result[index.getAndIncrement()] = value;
30+
} catch (InterruptedException e) {
31+
Thread.currentThread().interrupt();
32+
} finally {
33+
latch.countDown();
34+
}
35+
}).start();
36+
}
37+
38+
try {
39+
latch.await();
40+
} catch (InterruptedException e) {
41+
Thread.currentThread().interrupt();
42+
}
43+
44+
return result;
45+
}
46+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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 SleepSortTest {
8+
9+
@Test
10+
void testSleepSort() {
11+
int[] input = {5, 3, 6, 2, 10};
12+
int[] expected = {2, 3, 5, 6, 10};
13+
int[] result = SleepSort.sort(input);
14+
assertArrayEquals(expected, result);
15+
}
16+
17+
@Test
18+
void testEmptyArray() {
19+
int[] input = {};
20+
int[] expected = {};
21+
int[] result = SleepSort.sort(input);
22+
assertArrayEquals(expected, result);
23+
}
24+
25+
@Test
26+
void testSingleElement() {
27+
int[] input = {42};
28+
int[] expected = {42};
29+
int[] result = SleepSort.sort(input);
30+
assertArrayEquals(expected, result);
31+
}
32+
}

0 commit comments

Comments
 (0)