I am coding the non-recursive merge sort algorithm in Java I have to make sure if this method works as a non recursive as well as the space complexity should be O(N)
Instruction I got: You can use O(N) space (in addition to the input array) and your algorithm should have the same running time as recursive merge sort.
here's my code.
I want to make sure the recursiveness as well as the O(N) space If there's a better way, please let me know.
private static void merge(Integer[] a, Integer[] tmpArray, int leftPos, int rightPos, int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while(leftPos <= leftEnd && rightPos <= rightEnd) {
if( a[leftPos] <= a[rightPos ]) {
tmpArray[tmpPos++] = a[leftPos++];
} else {
tmpArray[tmpPos++] = a[rightPos++];
}
}
while( leftPos <= leftEnd ) { // Copy rest of first half
tmpArray[tmpPos++] = a[leftPos++];
}
while( rightPos <= rightEnd ) { // Copy rest of right half
tmpArray[tmpPos++] = a[rightPos++];
}
// Copy tmpArray back
for( int i = 0; i < numElements; i++, rightEnd-- ) {
a[rightEnd] = tmpArray[rightEnd];
}
}
public static void mergeSortB(Integer[] inputArray) {
Integer[] tempArray = new Integer[inputArray.length];
for(int i = 1; i<inputArray.length; i=i*2) {
for(int j=i; j<inputArray.length; j=j+i*2) {
int k = j+i-1;
if(inputArray.length<j + i) {
k = inputArray.length -1;
}
//call the merge method(non recursive)
merge(inputArray, tempArray, j-i,j, k);
}
}
}