实施MergeSort

时间:2019-04-30 11:01:45

标签: java arraylist

我实现了一个MergeSorting,它采用了通用数据类型,并且上下索引范围在经过这些范围之后停止了排序。示例{85,31,321,6549,123,2,1,0}下= 0上= 4将产生[31,85,123,321,6549,2,1,0]。虽然当我测试我的代码时,它给出了stackoverflow错误,但我不知道为什么。

我已经检查了我的代码,但是找不到问题,也许我没有边缘案例可以打破递归调用。

import java.util.ArrayList;
public class Sorts<T extends Comparable<? super T>> {
   public void merge(ArrayList<T> list, int start, int mid, int end)
   {
        ArrayList<T> tempArr = new ArrayList<T>(end - start);
        int leftidx = start;
        int rightidx = mid;
        while(true)
        {
            if (leftidx ==  mid)
            {
                tempArr.addAll(list.subList(rightidx,end)); 

                break;
            }
            else if (rightidx == end)
           {
                tempArr.addAll(list.subList(leftidx, mid));
                break;
           }

           T left = list.get(leftidx);
           T right = list.get(rightidx);

           int check = left.compareTo(right);

           if (check < 0) 
           {
               tempArr.add(left); 
               leftidx++; 
           }
           else
           {
               tempArr.add(right); 
               rightidx++; 
           }
        }

        for (int j = 0; j < tempArr.size(); j++)
        {
            list.set(start + j, tempArr.get(j));
        }




}
public void MergeSort(ArrayList<T> list, int start, int end) {

    int median = start + (end - start) / 2;
    MergeSort(list, start, median);
    MergeSort(list, median, end);
    merge(list, start, median, end);

   }
}

当我运行测试时,它在第82行给出错误“ java.lang.StackOverflowError”,这是我的mergesort类别中的MergeSort(list,start,median)。我的测试人员班是:

public class SortsTester extends Sorts{
    public void mergeSortTester{
       Integer [] arr = {85,31,321,6549,123,2,1,0};
       ArrayList<Integer> ranArrLst = new ArrayList<>(Arrays.asList(arr));
       MergeSort(ranArrLst,0,7);
       System.out.println(Arrays.toString(ranArrLst.toArray()));
     }
}

1 个答案:

答案 0 :(得分:0)

当元素少于两个时,您不应在MergeSort中执行任何操作:

public void MergeSort(ArrayList<T> list, int start, int end) {
    if ((end - start) < 2) {
        return;
    }
    int median = start + ((end - start) / 2);
    MergeSort(list, start, median);
    MergeSort(list, median, end);
    merge(list, start, median, end);
}