kruti-working-branch #14

Closed
kruti wants to merge 15 commits from kruti/Princeton1:kruti-working-branch into main
Showing only changes of commit 5a73f4ffda - Show all commits

View File

@ -7,6 +7,34 @@ import java.util.Arrays;
public class Merge<E> extends AbstractCustomSorts<E> { public class Merge<E> extends AbstractCustomSorts<E> {
@Override @Override
public void sort(E[] arr) { public void sort(E[] arr) {
merge_sort(arr, 0, arr.length-1);
}
private void merge_sort(E[] arr, int low_index, int high_index){
System.out.println(low_index + " " + high_index);
if(high_index - low_index > 0) {
int mid_index = low_index + (high_index - low_index)/2;
merge_sort(arr, low_index, mid_index);
merge_sort(arr, mid_index + 1, high_index);
// Copy array
hitanshu marked this conversation as resolved Outdated

Making a new aux arry with each recursive call is expensive

Making a new aux arry with each recursive call is expensive
E[] auxArr = (E[]) new Object[arr.length];
System.arraycopy(arr, 0, auxArr, 0, arr.length);
// Sort
int low_index_ptr = low_index;
int high_index_ptr = mid_index + 1;
for(int i=low_index; i<= high_index; i++){
if(low_index_ptr > mid_index)
arr[i] = auxArr[high_index_ptr++];
else if(high_index_ptr > high_index)
arr[i] = auxArr[low_index_ptr++];
else if(less((Comparable<E>) auxArr[low_index_ptr], auxArr[high_index_ptr]))
arr[i] = auxArr[low_index_ptr++];
else
arr[i] = auxArr[high_index_ptr++];
}
}
} }
} }