I need to split this array after it is sorted so that it prints something like
A: [8, 7, 6, 5]
B: [4, 3, 2, 1]
I know it might be simple but I cant figure it out. Do I need to do something like x.length / 2 ?
import java.util.Arrays;
public class RecursiveMerge
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] x= {8,7,5,6,2,4,3,1};
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(mergeSort(x)));
}
public static int [] mergeSort (int []a)
{
if(a.length ==1)
return a;
else
{
int mid = a.length/2;
int [] left =mergeSort(Arrays.copyOfRange(a, 0 , mid ));
int [] right =mergeSort(Arrays.copyOfRange(a, mid, a.length ));
mergeSort(left);
mergeSort(right);
return merge (left, right);
}
}
public static int[] merge (int[] left, int[] right)
{
int [] result = new int [left.length + right.length];
int leftPtr=0, rightPtr=0, resultPtr=0;
while(leftPtr < left.length && rightPtr < right.length)
if (left[leftPtr] < right [rightPtr])
result[resultPtr++] = left[leftPtr++];
else
result[resultPtr++] = right[rightPtr++];
while (leftPtr < left.length)
result[resultPtr++] = left[leftPtr++];
while (rightPtr <right.length)
result[resultPtr++] = right[rightPtr++];
return result;
}
}
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
To make it dynamically, do it based on array length and split it in two:
int [] x= {8,7,5,6,2,4,3,1};
int len = x.length;
int a[] = Arrays.copyOfRange(mergeSort(x), 0, len/2);
int b[] = Arrays.copyOfRange(mergeSort(x), (len/2), len);
System.out.println("A: " + Arrays.toString(a));
System.out.println("B: " + Arrays.toString(b));
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With