How to merge two sorted array in parallel?
I did follow this approach:
Basically getting the rank of each element in another array(number of elements before the current value) and placing in the correct index in the thirt array.
Is there any better way to solve this?
public static void merge(int[] a, int[]b ) throws InterruptedException {
int[] c = new int[a.length+b.length];
/**
* 1,2,5,7
* 3,4,6,8
*/
Thread t1 = new Thread(()->{
for(int i = 0; i<a.length; i++) {
int rank = rank(a[i],b);
System.out.print(rank+i);
c[rank+i] = a[i];
}
});
Thread t2 = new Thread(() -> {
for(int i = 0; i<b.length; i++) {
int rank = rank(b[i],a);
System.out.print(rank+i);
c[rank+i] = b[i];
}
});
t1.start();
t2.start();
Thread.sleep(2000);
System.out.println(Arrays.toString(c));
}
public static int rank (int a, int[] arr) { //O(Log(n))
int left = 0;
int right = arr.length;
while(left<right) {
int mid = left + (right - left)/2;
if(a < arr[mid]) {
right = mid;
} else {
left = mid+1;
}
}
return left;
}