java - What's wrong in this "mergeSort"? -


there's mergesort code copied @ class lesson, can me find errors?

when run main use mergesort program enters in infinite loop doesn't display error. tried run in debug mode not expert , don't find what's wrong. think error in mergesort(int[] v, int inf, int sup) recursion.

public class copyofsortmethods {  private static void merge(int[] v, int inf, int med, int sup) {     int aux[] = new int[v.length];     int = inf;     int j = med + 1;     int k = inf;      while ((i <= med) && (j <= sup)) {         if (v[i] < v[j]) {             aux[k] = v[i];             i++;             k++;         } else {             aux[k] = v[j];             j++;             k++;         }     }     while (i <= med) {         aux[k] = v[i];         i++;         k++;     }     while (j <= sup) {         aux[k] = v[j];         j++;         k++;     }     (i = 0; <= sup; i++) {         v[i] = aux[i];     } }  public static void mergesort(int[] v, int inf, int sup) {     int med;      while (inf < sup){         med = (inf + sup)/2;         mergesort(v, inf, med);         mergesort(v, med + 1, sup);         merge(v, inf, med, sup);     } }  public static void mergesort(int[] v) {     if(v!=null) {         mergesort(v, 0, v.length - 1);     }  } } 

the problems in merge sort (based in comments):

  1. in mergesort method, you're recursively calling mergesort inside while loop , never changing values of inf , sup. change if instead.

     if (inf < sup) {      //code goes here...  } 
  2. in merge sort, @ bottom of method body, you're moving items all items aux array v array. should move elements between inf , sup:

    //for (i = 0; <= sup; i++) { (i = inf; <= sup; i++) {     //code goes here... } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -