2

我正在使用 ArrayLists 的 MergeSort 算法,由于某种原因,错误的值被分配给我的变量。例如,如果我放入一个包含 4、5、4、2、1 的数组列表,它会输出为 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;
   } 
}
}
4

0 回答 0