'Trying to understand recursive merge sort
I'm using java, I have a code given by an instructor and I am trying ti follow the code but I can't seem to make the code work.
This is code given to us :
public class MergeSort {
@SuppressWarnings("unchecked") // Generic array allocation
public static <E extends Comparable<? super E>> void sort(E[] A) {
E[] temp = (E[])new Comparable[A.length];
mergesort(A, temp, 0, A.length-1);
}
public static <E extends Comparable<? super E>> void mergesort(E[] A, E[] temp, int l, int r) {
int mid = (l+r)/2; // Select midpoint
if (l == r) {
return; // List has one element
}
mergesort(A, temp, l, mid); // Mergesort first half
mergesort(A, temp, mid+1, r); // Mergesort second half
for (int i=l; i<=r; i++) // Copy subarray to temp
temp[i] = A[i];
// Do the merge operation back to A
int i1 = l; int i2 = mid + 1;
for (int curr=l; curr<=r; curr++) {
if ((i1< mid+1) && (i2<=r)) {
if (temp[i1].compareTo(temp[i2])<0) // Get smaller
A[curr] = temp[i1++];
else
A[curr] = temp[i2++];
}
else if ((i1==mid+1) && (i2 <= r) ){ // Left sublist exhausted
A[curr] = temp[i2++];
}
else if (i2 > r) { // Right sublist exhausted
A[curr] = temp[i1++];
}
}
}
}
so I added a main function inside the class Mergesort so I can follow the code using breakpoint and understand how merge sort uses recursion:
public static void main(String[] args) {
int Array []= {4,6,2,1,7,9,10};
MergeSort m=new MergeSort();
m.sort(Array);
}
but it does not work: I am getting this error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sort(E[]) in the type MergeSort is not applicable for the arguments (int[])
which is basically caused by m.sort(Array);
This is my entire code:
public class MergeSort {
public static void main(String[] args) {
int Array []= {4,6,2,1,7,9,10};
MergeSort m=new MergeSort();
m.sort(Array);
}
@SuppressWarnings("unchecked") // Generic array allocation
public static <E extends Comparable<? super E>> void sort(E[] A) {
E[] temp = (E[])new Comparable[A.length];
mergesort(A, temp, 0, A.length-1);
}
public static <E extends Comparable<? super E>> void mergesort(E[] A, E[] temp, int l, int r) {
int mid = (l+r)/2; // Select midpoint
if (l == r) {
return; // List has one element
}
mergesort(A, temp, l, mid); // Mergesort first half
mergesort(A, temp, mid+1, r); // Mergesort second half
for (int i=l; i<=r; i++) // Copy subarray to temp
temp[i] = A[i];
// Do the merge operation back to A
int i1 = l; int i2 = mid + 1;
for (int curr=l; curr<=r; curr++) {
if ((i1< mid+1) && (i2<=r)) {
if (temp[i1].compareTo(temp[i2])<0) // Get smaller
A[curr] = temp[i1++];
else
A[curr] = temp[i2++];
}
else if ((i1==mid+1) && (i2 <= r) ){ // Left sublist exhausted
A[curr] = temp[i2++];
}
else if (i2 > r) { // Right sublist exhausted
A[curr] = temp[i1++];
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
