【发布时间】:2019-03-10 17:09:09
【问题描述】:
我正在尝试在 Java 中创建一个 timSort 版本,它在 array.length
/**
* timSort is a generic sorting method that sorts an array of Comparable data
* using the TimSort algorithm. Make sure this method is public so that we can
* test it.
*
* @param data The array of data to be sorted
* @param <E> The Generic Element.
*/
public static <E extends Comparable<E>> void timSort(E[] data)
{
timSortHelper(data, 0, data.length - 1);
}
/**
* timSortHelper is a generic sorting method that sorts a sub-array array of
* Comparable data using the TimSort algorithm. This method should be public for
* testing purposes but would normally be private.
*
* Ranges are specified with the parameters left and right, which are inclusive.
*
* @param <E> The Generic Element.
* @param data The array of data to sort
* @param left The index of the left-most position to sort
* @param right The index of the right most position to sort
*/
public static <E extends Comparable<E>> void timSortHelper(E[] data, int left, int right)
{
// General Case: The sublist has at least one item in it.
if ((right - left) >= 1)
{
int middle1 = (left + right) / 2;
int middle2 = middle1 + 1;
if (data.length < 10)
{
insertionSort(data);
}
else
{
timSortHelper(data, left, middle1);
timSortHelper(data, middle2, right);
}
merge(data, left, middle1, middle2, right);
}
}
【问题讨论】:
-
调试你的程序。这是迄今为止找出问题是否立即可见的最简单方法。
-
调试器显示它正在选择正确的索引,但 data.length 没有作为较小的范围递归传递。这就是我无法理解递归调用在子数组的较小范围内传递但在测试长度是否
-
您的方法似乎与您描述的完全一样,但您对问题的表述与我怀疑您的意图不同。特别是,
array.length在回收期间不会改变——它始终是同一个数组对象的相同属性——所以你的方法要么立即使用插入排序,要么永远不会使用它。如果你想在处理数组的小间隔时切换到插入排序,那么你想测试right - left。 -
那么第二个 if 语句导致了错误?
标签: java arrays sorting generics timsort