简体   繁体   中英

Merge Sort in Java not working as expected. Trying to do it without a while loop

I've been working on this all day and have no idea why this isn't working. The sort is duplicating some elements and is sorting some of the array but I can't see what is causing this. Tried to trace it but couldn't follow it.

import java.io.FileNotFoundException;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) throws FileNotFoundException {

        int[] array = new int[10];
        for(int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random()*5);
        }

        int[] temp = array.clone();
        int l = 0;
        int r = array.length-1;
        System.out.println("unsorted "+Arrays.toString(array));
        mergeSort(array, temp, l, r);
        System.out.println("sorted "+Arrays.toString(array));
    }

    public static void mergeSort(int[] array, int[] temp, int p, int r) {
        int q = (p + r)/2;
        if(p < r) {
            mergeSort(array, temp, p, q);
            mergeSort(array, temp, q+1, r);
            merge(array, temp, p, q, r);
        }
    }

    public static void merge(int[] array, int[] temp, int p, int q, int r) {


        int i = p;
        int j = q + 1;

        for(int k = p; k < r; k++){
        if(i > q){
            array[k] = temp[j];
            j++;
        } else if(j > r) {
            array[k] = temp[i];
            i++;
        }  
        else if(temp[j] < temp[i]) {
            array[k] = temp[j];
            j++;
        } else {
            array[k] = temp[i];
            i++;
        }
      }
    }
}

Your code has two problems:

  1. Your for loop should be inclusive of r as it is the last index:

     for( int k = p; k <= r; k++ ) 
  2. You have to copy back to the temp at the end of your merge operation:

     for ( int k = p; k <= r; k++ ) { temp[ k ] = array[ k ]; } 

    or:

     System.arraycopy( array, p, temp, p, r + 1 - p ); 

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