递归MergeSort以优化空间

时间:2016-11-03 02:15:10

标签: java recursion mergesort

对于我的任务,我的任务是实现一个合并排序,它使用的是原始数组大小一半的临时数组。我很难理解如何使这个工作。它有时会工作,但某些值会使它不合适。任何帮助或方向都会有所帮助。现在是我现在的代码:

public void sort(T[] items) {

    // Your sort should work without allocating any more memory than this...
    T[] temp = (T[]) new Comparable[(items.length + 1) / 2];
    mergesort(items, temp, 0, items.length - 1);

}
private void mergesort(T[] items, T[] temp, int left, int right) {
    if (left == right) {
        return; // Region has one record
    }

    int mid = ((right + left)) / 2; // Select midpoint  
    mergesort(items, temp, left, mid); // Mergesort first half
    mergesort(items, temp, mid + 1, right);
    merge(items,temp,left,mid,right);
}

/**
 * Merge two sorted sub-arrays.
 */
private void merge(T[] items, T[] temp, int left, int mid, int right) {
    int count = 0;
    for (int i = left; i <= right; i++) {
        if (count == temp.length) {
            break;
        }
        temp[count] = items[i];// Copy subarray to temp
        count++;
    }

    int i1 = 0;
    int i2 = mid + 1;
    for (int curr = left; curr <= right; curr++) {
        if (i1 >= mid) { // Left subarray exhausted
            items[curr] = items[i2++];
        } else if (i2 > right) { // Right subarray exhausted
            items[curr] = temp[i1++];
        } else if (temp[i1].compareTo(items[i2]) <= 0) {
            items[curr] = temp[i1++];
        } else { // value
            items[curr] = items[i2++];
        }
    }

}

0 个答案:

没有答案