How to save CPU cycles when searching for a value in a sorted list?

后端 未结 6 1411
不思量自难忘°
不思量自难忘° 2021-02-10 05:16

In CodinGame learning platform, one of the questions used as an example in a C# tutorial is this one:

The aim of this exercise is to check the presence of

6条回答
  •  执念已碎
    2021-02-10 05:36

    If you are trying to squeeze every ounce of speed out of it... consider that your array has 1..100 and you want to search for 78. Your algorithm needs to search and compare 78 items before you find the right one. How about instead you search the first item and its not there, so you jump to array size / 2 and find 50? Now you skipped 50 iterations. You know that 78 MUST be in the top half of the array, so you can again split it in half and jump to 75, etc. By continuously splitting the array in half, you do much fewer iterations then your brute force approach.

提交回复
热议问题