Skip to content
Snippets Groups Projects
Commit 5c7e3d16 authored by Haley Glavina's avatar Haley Glavina
Browse files

Haley and Lawrence worked on Mergesort

parent d9ceae48
No related branches found
No related tags found
No related merge requests found
package sandbox; package sandbox;
public interface GeneralCompare<T> { public interface GeneralCompare {
public int eval(T a1, T a2); public int eval(Comparable a1, Comparable a2);
} }
package sort; package sort;
public interface GeneralCompare<T> { public interface GeneralCompare {
public int compare(T a1, T a2); public int compare(Comparable a1, Comparable a2);
} }
package sort; package sort;
import java.lang.reflect.Array;
public class MergeSort{ public class MergeSort{
private static Comparable[] aux; private static Comparable[] aux;
public static void merge(Comparable[] x, int lo, int hi, GeneralCompare gc){ public static void main(String[] args) {
GeneralCompare b1;
b1 = (a1, a2) -> (Integer) a1 - (Integer) a2;
Integer[] test = {3, 4, 2, 1, 5, 7, 9, 10};
sort(test, 0, Array.getLength(test) - 1, b1);
int n = hi - lo; for (int i = 0 ; i < (Array.getLength(test) - 1) ; i++) {
aux = new Comparable[n]; System.out.println(test[i]);
}
}
public static void sort(Comparable[] x, int lo, int hi, GeneralCompare gc) {
aux = new Comparable[Array.getLength(x)];
sortWrapped(x, 0, Array.getLength(x) - 1, gc);
}
private static void sortWrapped(Comparable[] x, int lo, int hi, GeneralCompare gc) {
int n = hi - lo;
if(n <= 1) if(n <= 1)
return; return;
// Recursively merge each half of the array // Recursively sort each half of the array
int mid = (n/2) + 1; int mid = lo + (n/2);
merge(x, lo, mid, gc); sortWrapped(x, lo, mid, gc);
merge(x, mid+1, hi, gc); sortWrapped(x, mid+1, hi, gc);
merge(x, lo, hi, gc);
}
private static void merge(Comparable[] x, int lo, int hi, GeneralCompare gc){
int n = hi - lo;
int mid = lo + (n/2);
// Fill auxiliary array // Fill auxiliary array
for(int k = 1; k <= n; k++){ System.out.println(n);
for(int k = lo; k <= hi; k++){
aux[k] = x[k]; aux[k] = x[k];
} }
// int i = 0;
while ((mid < hi) | (lo < mid)) { // Merging two sorted arrays
if (compare(aux[lo], aux[mid])) while ((lo <= mid) & (mid <= hi)) {
x[lo++] = mid; 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 // Is this portion sorting the aux array? Check
for(int k = 1; k <= n; k++){ for(int k = 1; k <= n; k++){
if(i > j-1) if(i > j-1)
...@@ -40,9 +64,7 @@ public class MergeSort{ ...@@ -40,9 +64,7 @@ public class MergeSort{
x[k] = aux[j++]; x[k] = aux[j++];
else else
x[k] = aux[i++]; 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