Java this is my current code i need help to implement public void sort method (T
ID: 3924972 • Letter: J
Question
Java
this is my current code i need help to implement public void sort method (TODO part)
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class MergeSort {
public static void sort(List<Integer> list) {
//TODO call the method private static void sort with parameters(length of input list, 0,0);
}
private static void sort(List<Integer> list, int startIndex, int endIndex){
int length = endIndex - startIndex;
if(length <= 1) {
return;
}
int middleIndex = startIndex + (length/2);
sort(list,startIndex,middleIndex);
sort(list,middleIndex,endIndex);
int upperStart = startIndex;
int upperEnd = startIndex + (length/2);
int lowerStart = upperEnd;
int lowerEnd = endIndex;
int i = upperStart;
int j = lowerStart;
List<Integer> tmpList = new ArrayList<Integer>();
while ( i < upperEnd || j < lowerEnd){
if(i >= upperEnd){
tmpList.add(list.get(j));
j++;
}
else if(j >= lowerEnd) {
tmpList.add(list.get(i));
i++;
}
else{
if(list.get(i) < list.get(j)){
tmpList.add(list.get(i));
i++;
}
else{
tmpList.add(list.get(j));
j++;
}
}
for(int k = startIndex; k < endIndex; k++){
list.set(k,tmpList.get(k - startIndex));
}
}
}
}
Explanation / Answer
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class MergeSort {
public static void sort(List<Integer> list) {
//call the method private static void sort with parameters(length of input list, 0,0);
sort(list.size(), 0,0);
}
private static void sort(List<Integer> list, int startIndex, int endIndex){
int length = endIndex - startIndex;
if(length <= 1) {
return;
}
int middleIndex = startIndex + (length/2);
sort(list,startIndex,middleIndex);
sort(list,middleIndex,endIndex);
int upperStart = startIndex;
int upperEnd = startIndex + (length/2);
int lowerStart = upperEnd;
int lowerEnd = endIndex;
int i = upperStart;
int j = lowerStart;
List<Integer> tmpList = new ArrayList<Integer>();
while ( i < upperEnd || j < lowerEnd){
if(i >= upperEnd){
tmpList.add(list.get(j));
j++;
}
else if(j >= lowerEnd) {
tmpList.add(list.get(i));
i++;
}
else{
if(list.get(i) < list.get(j)){
tmpList.add(list.get(i));
i++;
}
else{
tmpList.add(list.get(j));
j++;
}
}
for(int k = startIndex; k < endIndex; k++){
list.set(k,tmpList.get(k - startIndex));
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.