I just coded up this working version of mergesort:
static int[] merge(int[] first, int[] second){
int totalsize = first.length + second.length;
int[] merged_array = new int[totalsize];
int i = 0, firstpointer = 0, secondpointer = 0;
while(i < totalsize){
if(firstpointer == first.length){
merged_array[i] = second[secondpointer];
++secondpointer;
}
else if(secondpointer == second.length){
merged_array[i] = first[firstpointer];
++firstpointer;
}
else if(first[firstpointer] < second[secondpointer]){
merged_array[i] = first[firstpointer];
++firstpointer;
}
else{
merged_array[i] = second[secondpointer];
++secondpointer;
}
++i;
}
return merged_array;
}
static int[] mergesort(int[] array){
if(array.length == 1){
return array;
}
else{
int length = array.length;
int[] first = Arrays.copyOfRange(array, 0, (int) length / 2);
int[] second = Arrays.copyOfRange(array, (int) length / 2, length);
return merge(mergesort(first), mergesort(second));
}
}
However, if you notice, I use the copyOfRange function which creates a new array that is a copy of a certain portion of the parent array. Is there a mergesort implementation in java that is more space efficient than this?
Duplicate of: How to sort in-place using the merge sort algorithm?
Summary: Yes, there are memory-efficient merge-sorts, but they are either a) very complicated, or b) not time-efficient: O(n^2 log n)
Basically, don't bother. It's not actually that much memory that you're saving, and if you really want to, just use quicksort instead.