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):
in
mergesort
method, you're recursively callingmergesort
insidewhile
loop , never changing values ofinf
,sup
. changeif
instead.if (inf < sup) { //code goes here... }
in
merge
sort, @ bottom of method body, you're moving items all itemsaux
arrayv
array. should move elements betweeninf
,sup
://for (i = 0; <= sup; i++) { (i = inf; <= sup; i++) { //code goes here... }
Comments
Post a Comment