简体   繁体   中英

I'm having trouble getting MergeSort to work correctly

So far I have the following code:

public class MergeSort {
int[] theList;
int counter;  //required for analysis later
double time;  //required for analysis later

MergeSort(int[] n){
    int len = n.length;
    this.theList = mergeSort(n, 0, len);
}

int[] mergeSort(int[] n, int p, int r){
    if((p + 1 )<r){
        int q = (r + p)/2;
        mergeSort(n, p, q);
        mergeSort(n, q+1, r);
        merge(n, p, q, r);
    }
    return n;

}
public void merge(int[] input, int p, int q, int r){
    int lefti = q - p;
    int righti = r - q;
    int[] left = new int[lefti+1];
    int[] right = new int[righti+1];
    for(int i = 0; i < lefti; i++){
        this.counter++;
        left[i] = input[p+i];
    }
    for(int i = 0; i < righti; i++){
        this.counter++;
        right[i] = input[q+i];
    }
    left[left.length - 1] = 1000000;
    right[right.length - 1] = 1000000;
    int i = 0;
    int j = 0;
    for(int k = p; k < r; k++){
        this.counter++;
        if(left[i] < right[j]){
            input[k] = left[i];
            i++;
        }
        else{
            input[k] = right[j];
            j++;
        }
    }
}

}

I think I've been staring at this too long.I would appreciate if someone would be able to steer me in a better direction.

Right now, with the input of MergeSort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]), theList equals[4, 1, 0, 2, 3, 7, 5, 6, 8, 9].

I'm thankful for any help that I may receive.

It looks like you need a base case for your mergeSort method. If (p+1) >= r then sort the sub-array (ie the sub-array should have a size of 1 or 2, if it has a size of 1 then do nothing and if it has a size of 2 then swap the two values if they are out of order)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM