Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?

后端 未结 5 743
無奈伤痛
無奈伤痛 2021-01-03 21:19

Given an array having .length 100 containing elements having values 0 to 99 at the respective indexes, where the requirem

5条回答
  •  时光取名叫无心
    2021-01-03 22:26

    Since the element you're looking for is always roughly in the middle of the array, you should expect the version that walks inward from both the start and end of the array to take about twice as long as one that just starts from the beginning.

    Each variable update takes time, each comparison takes time, and you're doing twice as many of them. Since you know it will take one or two less iterations of the loop to terminate in this version, you should reason it will cost about twice as much CPU time.

    This strategy is still O(n) time complexity since it only looks at each item once, it's just specifically worse when the item is near the center of the list. If it's near the end, this approach will have a better expected runtime. Try looking for item 90 in both, for example.

提交回复
热议问题