Skip to content

Commit b36f359

Browse files
authored
Add Strand Sort (TheAlgorithms#3205)
1 parent 92bd9ba commit b36f359

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.thealgorithms.sorts;
2+
import java.util.Iterator;
3+
import java.util.LinkedList;
4+
5+
public class StrandSort{
6+
// note: the input list is destroyed
7+
public static <E extends Comparable<? super E>>
8+
LinkedList<E> strandSort(LinkedList<E> list){
9+
if(list.size() <= 1) return list;
10+
11+
LinkedList<E> result = new LinkedList<E>();
12+
while(list.size() > 0){
13+
LinkedList<E> sorted = new LinkedList<E>();
14+
sorted.add(list.removeFirst()); //same as remove() or remove(0)
15+
for(Iterator<E> it = list.iterator(); it.hasNext(); ){
16+
E elem = it.next();
17+
if(sorted.peekLast().compareTo(elem) <= 0){
18+
sorted.addLast(elem); //same as add(elem) or add(0, elem)
19+
it.remove();
20+
}
21+
}
22+
result = merge(sorted, result);
23+
}
24+
return result;
25+
}
26+
27+
private static <E extends Comparable<? super E>>
28+
LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){
29+
LinkedList<E> result = new LinkedList<E>();
30+
while(!left.isEmpty() && !right.isEmpty()){
31+
//change the direction of this comparison to change the direction of the sort
32+
if(left.peek().compareTo(right.peek()) <= 0)
33+
result.add(left.remove());
34+
else
35+
result.add(right.remove());
36+
}
37+
result.addAll(left);
38+
result.addAll(right);
39+
return result;
40+
}
41+
42+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.sorts;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.junit.jupiter.api.Assertions.*;
5+
6+
import java.util.Arrays;
7+
import java.util.LinkedList;
8+
9+
10+
class StrandSortTest {
11+
@Test
12+
// valid test case
13+
public void StrandSortNonDuplicateTest() {
14+
int[] expectedArray = { 1, 2, 3, 4, 5 };
15+
LinkedList<Integer> actualList = StrandSort.strandSort(new LinkedList<Integer>(Arrays.asList(3, 1, 2, 4, 5)));
16+
int[] actualArray = new int[actualList.size()];
17+
for (int i = 0; i < actualList.size(); i++) {
18+
actualArray[i] = actualList.get(i);
19+
}
20+
assertArrayEquals(expectedArray, actualArray);
21+
22+
}
23+
24+
@Test
25+
// valid test case
26+
public void StrandSortDuplicateTest() {
27+
int[] expectedArray = { 2, 2, 2, 5, 7 };
28+
LinkedList<Integer> actualList = StrandSort.strandSort(new LinkedList<Integer>(Arrays.asList(7, 2, 2, 2, 5)));
29+
int[] actualArray = new int[actualList.size()];
30+
for (int i = 0; i < actualList.size(); i++) {
31+
actualArray[i] = actualList.get(i);
32+
}
33+
assertArrayEquals(expectedArray, actualArray);
34+
35+
}
36+
37+
}
38+
39+

0 commit comments

Comments
 (0)