簡體   English   中英

通用MergeSort Java實現堆棧溢出錯誤

[英]Generic MergeSort Java Implementation Stack Overflow error

我正在嘗試用Java編寫通用的Merge排序方法。

這是我的源代碼:

import java.util.ArrayList;
import java.util.List;

/**
 * An implementation of MergeSort
 *
 * @param <T> the type of data held by the array.
 */
public class MergeSort<T extends Comparable<? super T>> implements ArraySort<T>
{
    /**
     * Sort the array using a MergeSort.
     *
     * (recursively breaks down the array into sub arrays until arrays of size 1 are reached.)
     * (then works backwards merging these arrays back into each other until a sorted array state is reached containing
     *  all the elements of the initial unsorted array, but now sorted).
     *
     * @param array the array to be sorted.
     * @return array (sorted)
     */
    @Override
    public T[] sort(T[] array)
    {
        //If the array being sorted is less than 2 elements, it is already sorted and cannot be split into two separate
        //     arrays, so return the initial array to prevent an exception.
        if(array.length < 2)
        {
            return array;
        }

        //Create two sub arrays from the initial array passed in.
        T[] temp1 = copy(array, 0, (array.length/2) - 1);
        T[] temp2 = copy(array, (array.length/2), array.length - 1);

        //Sort these two arrays.
        sort(temp1);
        sort(temp2);

        //Merge the two subarrays back into the initial array.
        merge(array, temp1, temp2);

        //return the now sorted array.
        return array;
    }

    /**
     * Create and return a new array, comprised of a sublist of a passed in array.
     *
     * @param list the array to create the subarray from.
     * @param from the lower bound within list to copy.
     * @param to the upper bound within list to copy.
     * @return a new list comprised of the elements from 'from' to 'to' in 'list'
     */
    private <T> T[] copy(T[] list, int from, int to)
    {
        List<T> copyL = new ArrayList<>();
        for(int i = 0; i < to - from + 1; i++)
        {
            copyL.add(list[from + i]);
        }
        return copyL.toArray(list);
    }

    /**
     * Merge two sorted arrays into one larger array, keeping the sorted.
     *
     * @param target the array to merge source1 and source2 into.
     * @param source1 a sorted array
     * @param source2 a second sorted array.
     */
    private void merge(T[] target, T[] source1, T[] source2)
    {
        //Variables to keep track of the smallest unused element in each source array.
        int source1Index = 0;
        int source2Index = 0;

        //targetIndex keeps track of the next index to place the next smallest element into.
        for(int targetIndex = 0; targetIndex < target.length; targetIndex++)
        {
            //Choose the smallest element from the two source arrays to place into the target(sorted) array
            if(source1[source1Index].compareTo(source2[source2Index]) < 0)
            {
                target[targetIndex] = source1[source1Index];
                source1Index++;
            }
            else
            {
                target[targetIndex] = source2[source2Index++];
                source2Index++;
            }
        }
    }
}

我不知道為什么,但是在調用第38和42行時出現了StackOverflow錯誤。

38 = T[] temp1 = copy(...) in the sort() method
42 = sort(temp1) in the sort() method.

這使我相信錯誤是在復制功能中的某處,但是我不知道如何解決問題或尋求解決方案。

有人可以幫我解決這種通用合並排序的實現嗎?

StackTrace用於對12個元素的數組進行排序。

https://docs.google.com/document/d/1Ig5p7TZF_eX0Q_rroORnZUWnXtep7x-7cmDiSAZWlj8/edit?usp=sharing

您的條件還不夠好,您會在數組上收到無限的排序調用。

至少您應該包含大小等於2的數組:

if(array.length <= 2)

另外,必須改進您的復制方法。

無論如何,請復制/粘貼您的完整堆棧跟蹤。

您的陣列復制錯誤。

采用:

    private <T> T[] copy(T[] list, int from, int to) {
        return Arrays.copyOfRange(list, from, to);
    }

您的代碼中還有更多錯誤( merge不會處理不同長度的數組),但這應該可以解決您的問題。

參見List.toArray(T [])

...如果列表適合指定的數組,則會在其中返回。

也就是說,您要復制到原始陣列中,而不是創建新陣列,因此您的陣列實際上不會減小大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM