合并排序但不递归不会排序数组的最后一个元素

时间:2019-04-24 02:43:12

标签: java mergesort

我正在尝试创建不使用递归的mergeSort方法。它几乎可以完美地工作,除了由于某种原因不能对数组的最后一个元素进行排序。任何帮助是极大的赞赏!

示例输出:

[23, 94, 69, 32, 99, 20, 17, 88, 22, 88]

MergeSort用了7.134364毫秒

原始:[17, 20, 22, 23, 32, 69, 88, 88, 94, 99] //Arrays.sort

working1:[17, 20, 22, 23, 32, 68, 88, 94, 99, 88] //MergeSort

有错误

import java.util.*;

public class MergeSort {
public static void mergeSortExplicit(int[] arr, int n){
    int size;  
    int left; 

    for (size = 1; size <= n-1; size = 2*size) {  
        for (left = 0; left < n-1; left += 2*size) { 
            int mid = left + size - 1; 

            int right = Math.min(left + 2*size - 1, n-1);

            merge(arr, left, mid, right);
        } 
    } 
 }
private static void merge(int[] array, int start, int mid, int end) {
    int leftIndex = start;
    int rightIndex = mid + 1;
    int[] temp = new int[end - start + 1];
    int tempIndex = 0;

    while (leftIndex <= mid && rightIndex <= end) {

        temp[tempIndex++] = (array[leftIndex] < array[rightIndex]) ? array[leftIndex++] : array[rightIndex++];

    }

    if (leftIndex <= mid) {
        System.arraycopy(array, leftIndex, temp, tempIndex, mid - leftIndex + 1);
    }

    if (rightIndex <= end) {
        System.arraycopy(array, rightIndex, temp, tempIndex, end - rightIndex + 1);
    }

    System.arraycopy(temp, 0, array, start, end - start + 1);

}

public static final void main(String[] args) {
    Random random = new Random();
    int[] original = new int[10];
    for (int i = 0; i < original.length; i++) {
        original[i] = random.nextInt(original.length * 10);
    }
    int[] working1 = new int[original.length];
    System.arraycopy(original, 0, working1, 0, original.length);

    long startTime = 0, endTime = 0;

    startTime = System.nanoTime();
    Arrays.sort(original);
    endTime = System.nanoTime();
    System.out.println("Arrays.sort() took " + ((endTime - startTime) / 1E6) + " milliseconds");

    startTime = System.nanoTime();
    //mergeSort(working1, 0, working1.length - 1);
     System.out.println(Arrays.toString(working1));
    mergeSortExplicit(working1, working1.length - 1);
    endTime = System.nanoTime();
    System.out.println("MergeSort took " + ((endTime - startTime) / 1E6) + " milliseconds");

    if (!Arrays.equals(original, working1)) {
        System.out.println("original: " + Arrays.toString(original));
        System.out.println("Working1: " + Arrays.toString(working1));
        System.out.println("There is an error");
    } else {
        System.out.println("Sorts Work!");
    }
}

}

1 个答案:

答案 0 :(得分:0)

刚通过时,我可以看到您正在main中调用以下函数:

mergeSortExplicit(working1, working1.length - 1);

这意味着您已经以比实际大小小1的大小调用了函数,然后在下面的循环中再次在该调用的函数内部进行了调用:

for (size = 1; size <= n-1; size = 2*size)

您再考虑比通过的减1。

请删除上述任何一项减免,然后应该可以正常工作。