python: find value within range in float array

前端 未结 2 507
生来不讨喜
生来不讨喜 2021-01-27 15:10

I have the following sorted python list, although multiple values can occur:

[0.0943200769115388, 0.17380131294164516, 0.4063245853719435, 
 0.45796523225774904,         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-27 15:46

    If you know the list is already sorted, then the textbook solution is to do a binary search. You keep two index bounds, min and max. Initialize them to 0 and len - 1. Then set mid to be (min + max) / 2. Compare the value at index mid with your target value. If it's less, then set min to mid + 1. If it's greater, then set max to mid - 1. Repeat until you either find the value or until max < min, in which case you will have found the desired index in O(log(n)) steps.

提交回复
热议问题