forked from Hithomelabs/Princeton1
Merge sort implementation
This commit is contained in:
parent
d091dc4c5d
commit
5a73f4ffda
@ -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
|
||||||
|
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++];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user