Dec
12
Java: MergeSort
Fully functional but I still can’t quite understand the syntax. I know the logic but Java is new to me, so it needs a lot of debugging time ^_^
—-Beginning of Code—-
import java.io.*;
public class MergeSortArray {
private long[] theArray;
private int nElems;
public MergeSortArray(int max) {
theArray = new long[max];
nElems = 0;
}
public void insert(long value) {
theArray[nElems] = value; // insert it
nElems++; // increment size
}
public void display() {
for (int j = 0; j < nElems; j++)
System.out.print(theArray[j] + " ");
System.out.println("");
}
public void mergeSort() {
long[] workSpace = new long[nElems];
recMergeSort(workSpace, 0, nElems - 1);
}
private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) {
if (lowerBound == upperBound) // if range is 1,
return; // no use sorting
else { // find midpoint
int mid = (lowerBound + upperBound) / 2;
// sort low half
recMergeSort(workSpace, lowerBound, mid);
// sort high half
recMergeSort(workSpace, mid + 1, upperBound);
// merge them
merge(workSpace, lowerBound, mid + 1, upperBound);
}
}
private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) {
int j = 0; // workspace index
int lowerBound = lowPtr;
int mid = highPtr - 1;
int n = upperBound - lowerBound + 1; // # of items
while (lowPtr <= mid && highPtr <= upperBound)
if (theArray[lowPtr] < theArray[highPtr])
workSpace[j++] = theArray[lowPtr++];
else
workSpace[j++] = theArray[highPtr++];
while (lowPtr <= mid)
workSpace[j++] = theArray[lowPtr++];
while (highPtr <= upperBound)
workSpace[j++] = theArray[highPtr++];
for (j = 0; j < n; j++)
theArray[lowerBound + j] = workSpace[j];
}
public static void main(String[] args) {
int maxSize = 100; // array size
MergeSortArray arr = new MergeSortArray(maxSize); // create the array
System.out.print("How many input? [1-100]: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer howMany = null;
try {
howMany = Integer.parseInt(br.readLine());
} catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
for(int i=1; i<=howMany; i++){
System.out.print("Enter number " + i + ": ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
Integer iNum = null;
try {
iNum = Integer.parseInt(br1.readLine());
} catch (IOException err) {
System.out.println("Invalid Input!");
System.exit(1);
}
arr.insert(iNum);
}
arr.display();
arr.mergeSort();
arr.display();
}
}
—-End of Code—-

