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


i've been working on day , have no idea why isn't working. sort duplicating elements , sorting of array can't see causing this. tried trace 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 = 0; < 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 = 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 2 problems:

  1. your for loop should inclusive of r last index:

    for( int k = p; k <= r; k++ ) 
  2. you have copy temp @ end of merge operation:

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

    or:

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

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -