algorithm - Understanding why Java selection rank returns max() as final result -
i working out solution following question:
describe algorithm find smallest 1 million numbers in 1 billion numbers. assume computer memory can hold 1 billion numbers.
the book gives selection rank solution having hard time understanding few parts of it:
public static int partition(int[] array, int left, int right, int pivot) { while (true) { while (left <= right && array[left] <= pivot) { left++; } while (left <= right && array[right] > pivot) { right--; } if (left > right) { return left - 1; } swap(array, left, right); } } public static int rank(int[] array, int left, int right, int rank) { int pivot = array[randomintinrange(left, right)]; int leftend = partition(array, left, right, pivot); // returns end of left partition int leftsize = leftend - left + 1; if (leftsize == rank + 1) { return max(array, left, leftend); } else if (rank < leftsize) { return rank(array, left, leftend, rank); } else { return rank(array, leftend + 1, right, rank - leftsize); } }
i understand of it, no understand following 2 lines above:
if (leftsize == rank + 1) { return max(array, left, leftend);
1. why returning max of 3 variables?
2. shouldn't returning array[left:leftend]
or of nature?
congratulations on trying learn studying book. it's key skill seems getting rarer.
it makes general sense if definition of return value of rank
"there exist million numbers less or equal rank
." definition of max
like:
int t = array[left]; (int = left + 1; <= leftend; i++) t = math.max(t, array[i]); return t;
returning max value beyond problem statement , kind of weird. better , simpler partition elements max million @ top: array[0] through array[999999]
. find max if that's needed
note because rank
tail recursive, there's simple iterative version of same code think clearer.
i'm not convinced code correct. leftsize == rank
in check makes more sense leftsize == rank + 1
. without more definitions , calling code, it's hard sure.
Comments
Post a Comment