How to implement mergeSort?

225 views Asked by At

I am trying to implement a recursive mergesort but the method is writting only zeros in the sorted vector. Here is my code. At the main function i just read the values to a vector and pass it as argument to mergesort. Any ideias of what i am doing wrong? Thank you.

public static void mergesort(int []  v){
int mid=v.length/2;

if( v.length < 2)
    return;

int l[]=new int [mid];
int r[] = new int [v.length-mid];

for(int i=0; i<mid-1; i++)
    l[i]=v[i];

for(int i=mid; i<v.length-1; i++)
    r[i-mid]=v[i];

mergesort(l);
mergesort(r);
mergesort(l,r,v); 


}

public static void mergesort(int [] l, int [] r, int [] v){
int i=0, j=0, k=0;

while(i< l.length && j< r.length){

    if(l[i] <= r[j]){
    v[k]=l[i];
    i++;
    }
    else{
    v[k]=r[j];
    j++;
    }
k++;
}

while(i < l.length){
    v[k]=l[i];
    i++;
    k++;
}

while(j< r.length){
    v[k]=r[j];
    j++;
    k++;
}
}
2

There are 2 answers

0
Mudit On BEST ANSWER

Suppose you input a vector of size 2; then according to your code

mid=1;

for(int i=0;i<mid-1;i++)

// here   i < (1-1)   which will never execute

    l[i]=v[i];
0
Gobinath On

There are two mistakes in the algorithm.

Mistake 1:

while (i < r.length && j < r.length) {
    if (l[i] <= r[j]) {
        v[k] = l[i];
        i++;
    } else {
        v[k] = r[j];
        j++;
    }
    k++;
}

Here the i must be less than l.length. This is the reason for ArrayIndexOutOfBoundsException if l.length != r.length.

Mistake 2:

for (int i = 0; i < mid - 1; i++)
    l[i] = v[i];

for (int i = mid; i < v.length - 1; i++)
    r[i - mid] = v[i];

The i's range must be 0 to (mid - 1). So the for loop should use <= operator in both places like this:

for (int i = 0; i <= mid - 1; i++)
    l[i] = v[i];

for (int i = mid; i <= v.length - 1; i++)
    r[i - mid] = v[i];

This is the reason for getting zeros.

The modified code is given below:

public static void mergesort(int []  v) {
    int mid = v.length / 2;

    if ( v.length < 2)
        return;

    int l[] = new int [mid];
    int r[] = new int [v.length - mid];

    for (int i = 0; i <= mid - 1; i++)
        l[i] = v[i];

    for (int i = mid; i <= v.length - 1; i++)
        r[i - mid] = v[i];

    mergesort(l);
    mergesort(r);
    mergesort(l, r, v);
}

public static void mergesort(int [] l, int [] r, int [] v) {
    int i = 0, j = 0, k = 0;

    while (i < l.length && j < r.length) {
        if (l[i] <= r[j]) {
            v[k] = l[i];
            i++;
        } else {
            v[k] = r[j];
            j++;
        }
        k++;
    }

    while (i < l.length) {
        v[k] = l[i];
        i++;
        k++;
    }

    while (j < r.length) {
        v[k] = r[j];
        j++;
        k++;
    }
}