
Merge Sorting
Can anyone please help me with this? Appreciate it a lot.
I am to code a merge method for sorting an array of n size which uses another array of b of size n/2. Here is what I have so for:
My main method has:
int[] random ={1,7,8,10,2,4,5,6};
mergeHalf(random,new int [random.length/2 + random.length%2],0,3,7);
This should work for n= 32 etc. In this example, random is sorted from index 03 and 47, that is why method call is 0,3,7. Tried to figure it out with this example, but I have a sort method as well that will sort the 2 halves of array and then call the mergeHalf method.
b is initially an empty size of n/2 ( 4 elements with this example of random 8 elements) and is used as a temp array . For now, it only sorts the first 4 elements of random.
Thanks a lot
public static void mergeHalf(int[] a, int[] b, int i, int j, int k) {
int leftEnd = j;
int tmpPos = i;
// int numElements = k  i + 1;
int jCount=0;//number of elements removed from 2nd part of a
while (i <= leftEnd && j + 1 <= k) {
if (tmpPos >= b.length){
printArray("A", a);
//shift
for(int s = i; s<=leftEnd; s++){
a[s+jCount]=a[s];
}
//j+= jCount;
i+= jCount;
//assign A from B
for (int i1=0; i1 < b.length; i1++){
a[i1] = b[i1];
}
jCount=0;
tmpPos=0;
leftEnd= j;
printArray("A", a);
printArray("B", b);
//System.exit(0);
}
if (a[i] <= a[j + 1])
b[tmpPos++] = a[i++];
else{
b[tmpPos++] = a[j++ +1];
jCount++;
}
}