1. Implement a method to sort a given array using the merge sort algorithm. Use
ID: 3783461 • Letter: 1
Question
1. Implement a method to sort a given array using the merge sort algorithm. Use the algorithm provided (below) instead of the algorithm from the textbook. NOTE: You have to allocate tempo array in the main method and copy the original input array A to the temp array before invoking merge sont in the main method. MERGE-SORT (A, temp. p.) MERGE-SORT (A, temp, p ,q) MERGE-SORT (A, temp, q 1 r) MERGE (A, temp, p, q, r) MERGE (A temp, p, q. merge Alp q with Alq 1-1 j a q 1 copy Alp..rn to templp..rl for k p to r templkl Alk] copy Alp, r to templp.rl for k a p to r I of 2 CS303 Lab Assignment llmerge back to Alp.rl for k a p to r if i q left half empty, copy from the right Aukl a tempUl else ifj r right half empty copy from the left else if tempU]Explanation / Answer
package com.java2novice.sorting;
public class MyMergeSort {
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String a[]){
int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.