Skip to content
Snippets Groups Projects
Commit 02e042bc authored by Christopher Schankula's avatar Christopher Schankula :earth_africa:
Browse files

make MergeSort and GeneralCompare typesafe

parent edb185ee
No related branches found
No related tags found
No related merge requests found
package sort;
public interface GeneralCompare {
public int compare(Comparable a1, Comparable a2);
public interface GeneralCompare<T> {
public int compare(Comparable<T> a1, Comparable<T> a2);
}
......@@ -3,11 +3,9 @@ package sort;
import java.lang.reflect.Array;
public class MergeSort{
private static Comparable[] aux;
public static void main(String[] args) {
GeneralCompare b1;
GeneralCompare<Integer> b1;
b1 = (a1, a2) -> (Integer) a1 - (Integer) a2;
Integer[] test = {3, 4, 2, 1, 5, 7, 9, 10, 11};
//Integer[] test = {2, 1};
......@@ -18,23 +16,24 @@ public class MergeSort{
}
}
public static void sort(Comparable[] x, int lo, int hi, GeneralCompare gc) {
aux = new Comparable[x.length];
sortWrapped(x, lo, hi, gc);
public static <T> void sort(Comparable<T>[] x, int lo, int hi, GeneralCompare<T> gc) {
Comparable<T>[] aux;
aux = (Comparable<T>[]) new Comparable[x.length];
sortWrapped(x, lo, hi, gc, aux);
}
private static void sortWrapped(Comparable[] x, int lo, int hi, GeneralCompare gc) {
private static <T> void sortWrapped(Comparable<T>[] x, int lo, int hi, GeneralCompare<T> gc, Comparable<T>[] aux) {
int n = hi - lo;
if(n < 1)
return;
// Recursively sort each half of the array
int mid = lo + (n/2);
sortWrapped(x, lo, mid, gc);
sortWrapped(x, mid+1, hi, gc);
merge(x, lo, hi, gc);
sortWrapped(x, lo, mid, gc, aux);
sortWrapped(x, mid+1, hi, gc, aux);
merge(x, lo, hi, gc, aux);
}
private static void merge(Comparable[] x, int lo, int hi, GeneralCompare gc){
private static <T> void merge(Comparable<T>[] x, int lo, int hi, GeneralCompare<T> gc, Comparable<T>[] aux){
int n = hi - lo;
int mid = lo + (n/2);
......@@ -58,31 +57,5 @@ public class MergeSort{
else
x[k] = aux[i++];
}
/*
int i = 0;
// Merging two sorted arrays
while (i <= n) {
if (gc.compare(aux[lo], aux[mid]) > 0)
x[i++] = aux[mid++];
else
x[i++] = aux[lo++];
}
*/
/*
// Is this portion sorting the aux array? Check
for(int k = 1; k <= n; k++){
if(i > j-1)
x[k] = aux[j++];
else if(j > n)
x[k] = aux[i++];
else if(gc.compare(aux[j+1],aux[1]) < 0)// ?
x[k] = aux[j++];
else
x[k] = aux[i++];
}*/
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment