Last active
August 21, 2020 13:59
-
-
Save MasFlam/bbc7094b5aa11d4f7ce33220cf10d556 to your computer and use it in GitHub Desktop.
ForkBombSort or ForkSort is a version of MergeSort, where on every recursion, two new threads are created.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class ForkSort { | |
private ForkSort() {} | |
public static <T> List<T> forkSort(List<T> list, Comparator<T> comp) { | |
int len = list.size(); | |
int mid = len / 2; | |
List<T> one = new ArrayList<>(mid); | |
List<T> two = new ArrayList<>(len - mid); | |
Thread th1 = new Thread(() -> | |
one.addAll(forkSort(list.subList(0, mid))) | |
); | |
Thread th2 = new Thread(() -> | |
two.addAll(forkSort(list.subList(mid, len))) | |
); | |
th1.start(); | |
th2.start(); | |
try { | |
th1.join(); | |
th2.join(); | |
} catch(InterruptedException e) { | |
return Collections.emptyList() | |
} | |
if(one.isEmpty() || two.isEmpty()) { | |
return Collections.emptyList(); | |
} | |
return merge(one, two, comp); | |
} | |
private static <T> List<T> merge(List<T> one, List<T> two, Comparator<T> comp) { | |
int len1 = one.size(); | |
int len2 = two.size(); | |
List<T> out = new ArrayList<>(len1 + len2); | |
int i = 0; | |
int j = 0; | |
while(i < len1 && j < len2) { | |
T a = one.get(i); | |
T b = two.get(j); | |
int cmp = comp(a, b); | |
if(cmp > 0) { | |
out.add(a); | |
++i; | |
} else { | |
out.add(b); | |
++j; | |
} | |
} | |
while(i < len1) { | |
out.add(one.get(i)); | |
++i; | |
} | |
while(j < len2) { | |
out.add(two.get(j)); | |
} | |
return out; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment