/ / Java ArrayList zlúčiť triedenie algoritmus - java, mergesort

Java ArrayList zlúčiť triedenie algoritmus - java, mergesort

Mám nejaké problémy s algoritmom zlúčenia v jazyku Java. Zdá sa, že teraz robí veľa divných vecí a ja mám problémy s tým, ako sa dostanem do práce. Verím, že problém by mohol ležať niekde v mergeArrayLists ale nie som si istý, akákoľvek pomoc by bola ocenená!

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;
}
}

odpovede:

0 pre odpoveď č. 1

Máte vypnutý o jednu chybu.

for(firstIndex=0; firstIndex<firstList.size(); firstIndex++) {
while(secondIndex < secondList.size()) {
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));
}

Vaše zoznamy by mali byť index <veľkosť nie veľkosť -1