我正在使用带有ArrayLists的MergeSort算法,出于某种原因,我的变量分配了错误的值。例如,如果我输入一个带有4,5,4,2,1的arraylist,它就会显示为1,2,4,5,4。我刚从中学毕业,想在夏天玩Java。有人可以帮帮我吗?
import java.util.*;
public class MergeSort{
public ArrayList c;
private Comparable tempLargest;
public MergeSort()
{
}
public void merge (ArrayList <Comparable> a, ArrayList <Comparable> b, ArrayList <Comparable> c) {
int i2 = 0;
int i1 = 0;
c.clear();
for (int i = 0; i < Math.max(a.size(), b.size());i++){
if(a.size()+b.size() != c.size()){
if (i2 >= b.size()){
while(i<a.size()){
c.add(a.get(i));
i++;
}
break;
} else if (i1 >= a.size()){
while(i<b.size()){
c.add(b.get(i));
i++;
}
break;
} else if (a.get(i1).compareTo(b.get(i2)) < 0){
tempLargest = b.get(i2);
while(i1 < a.size() && a.get(i1).compareTo(tempLargest)<=0 ){
c.add(a.get(i1));
i1++;
}
c.add(tempLargest);
i2++;
} else if (a.get(i1).compareTo(b.get(i2)) >= 0){
tempLargest = a.get(i1);
while(i2 < b.size() && b.get(i2).compareTo(tempLargest)<=0){
c.add(b.get(i2));
i2++;
}
c.add(tempLargest);
i1++;
}
}
}
}
public void mergeSort(ArrayList <Comparable> ary){
ArrayList a = new ArrayList<Comparable>();
ArrayList b = new ArrayList<Comparable>();
ArrayList c = new ArrayList<Comparable>();
int n = ary.size();
if (n == 1){
} else if (n ==2 ){
if (ary.get(0).compareTo(ary.get(1))>0){
Comparable temp = ary.get(0);
ary.set(0, ary.get(1));
ary.set(1, temp);
}
}else{ // divide list into two halves
int mid = (n+1)/2;
for (int i = 0; i < n; i++){
if(i<mid){
a.add(ary.get(i));
}
else{
b.add(ary.get(i));
}
}
mergeSort(a);
mergeSort(b);
merge(a,b,c);
ary = c;
}
}
}