sorting - Java If-Statement in Merge Sort... Why does this work? -
i learning implement of more simple algorithms in java, can't figure out why statement works:
private void domergesort(int lowerindex, int higherindex) { if (lowerindex < higherindex) { int middle = lowerindex + (higherindex - lowerindex) / 2; domergesort(lowerindex, middle); domergesort(middle + 1, higherindex); mergeparts(lowerindex, middle, higherindex); } }
i have gone through debug, , don't understand how possible second instance of domergesort called - domergesort(middle + 1, higherindex); - when final iteration of previous domergesort feeding 0, 0 method. wouldn't cause if statement return false, , second domergesort call not execute?
this code run, , result correct, how possible?
i think source of confusion sounds think variables lowerindex
, middle
, higherindex
modfied across recursive calls. don't. each recursive call gets it's own separate copy of fields 2nd call domergesort(middle + 1, higherindex);
doesn't use updated middle
, higherindex
, uses whatever values when passed domergesort(int lowerindex, int higherindex)
so if print variables @ each call were, this...
domergesort(0,9) domergesort(0,4) domergesort(0,2) domergesort(0,1) domergesort(0,0) domergesort(1,1) mergeparts(0,0,1) domergesort(2,2) mergeparts(0,1,2) domergesort(3,4) domergesort(3,3) domergesort(4,4) mergeparts(3,3,4) mergeparts(0,2,4) domergesort(5,9) domergesort(5,7) domergesort(5,6) domergesort(5,5) domergesort(6,6) mergeparts(5,5,6) domergesort(7,7) mergeparts(5,6,7) domergesort(8,9) domergesort(8,8) domergesort(9,9) mergeparts(8,8,9) mergeparts(5,7,9) mergeparts(0,4,9)
Comments
Post a Comment