0
Java의 병합 정렬 알고리즘에 문제가 있습니다. 지금은 이상한 일들이 많이 일어나고 있고, 일하기가 어려워요. 이 문제는 mergeArrayLists
함수의 어딘가에 있을지 모르지만 확실하지 않습니다. 어떤 도움을 주시면 감사하겠습니다!Java ArrayList 병합 정렬 알고리즘
public class MergeSort extends Sort {
public MergeSort() {
}
// Inherited from Sort
public <T extends Comparable<T>> void sortArrayList(ArrayList<T> arrayList) {
arrayList = mergeSort(arrayList);
}
// Returns the sorted form of the given array list (sorted via the merge sort algorithm)
public <T extends Comparable<T>> ArrayList<T> mergeSort(
ArrayList<T> arrayList) {
if (arrayList.size() <= 1) {
return arrayList;
} else {
ArrayList<T> firstList = new ArrayList<T>();
ArrayList<T> secondList = new ArrayList<T>();
for (int i = 0; i < arrayList.size(); i++) {
T thisValue = arrayList.get(i);
if (i < arrayList.size()/2) {
firstList.add(thisValue);
} else {
secondList.add(thisValue);
}
}
//System.out.println(firstList+" "+mergeSort(firstList));
ArrayList<T> firstSort = mergeSort(firstList);
ArrayList<T> secondSort = mergeSort(secondList);
return mergeArrayLists(firstSort, secondSort);
}
}
// Merges two array lists together, in order
public <T extends Comparable<T>> ArrayList<T> mergeArrayLists(
ArrayList<T> firstList, ArrayList<T> secondList) {
ArrayList<T> resultList = new ArrayList<T>();
int firstIndex, secondIndex = 0;
for (firstIndex = 0; firstIndex < firstList.size() - 1; firstIndex++) {
while (secondIndex < secondList.size() - 1) {
if (firstList.get(firstIndex)
.compareTo(secondList.get(secondIndex)) < 0) {
break;
} else {
resultList.set(firstIndex + secondIndex,
secondList.get(secondIndex));
secondIndex++;
}
}
resultList.set(firstIndex + secondIndex, firstList.get(firstIndex));
}
System.out.println(firstList + " + " + secondList + " = " + resultList);
return resultList;
}
}
해야 하는가? 실패한 몇 가지 예를 보여주십시오 : 입력, 예상 출력, 실제 출력. 또한 - 디버거를 사용하여 문제를 특정 문제에 집중해야합니다. – amit
숙제 인 경우 숙제 태그를 추가하십시오. – home