“Programming Pearls” binary search help

非 Y 不嫁゛ 提交于 2019-11-30 05:01:45

After each pass your next pass will be on the smaller of the two lists you've compiled.

At some point, you MUST encounter an empty list and this will determine your number. For example let's just use 3 bit numbers.

000
001
110
100
111

after the first pass we have

000
001

110
100
111

Then we look at the 2nd bits in the first list because it is smaller than (or equal to) the second. We would split them into

000
001

empty list

notice how the file that would start with 01 is empty, this means that there are no numbers that start with 01 so 010 and 011 are missing.

The reason we must eventually have a missing list is because we are choosing the smaller list for our next pass each time.

Eventually, if you keep splitting, you will have (at most) 4 billion files, each with one integer in it. In theory, you will then "know" which one is missing because there won't be a file for it.

You might also end up with a situation where you have an odd number of integers. In that case, the smaller half will be missing a number. This makes it easier to home in on the missing number.

In the case where you have an even number, you know that two are missing. In this case, you must find the parts that are smaller than their respective halves, and then proceed with the solution above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!