Ask Your Question

Revision history [back]

One way to obtain the position of an index in a sorted list without utilizing any pre-existing functions is to use binary search algorithm.

The binary search algorithm works as follows:

  1. Define two pointers, low and high, to represent the start and end of the list respectively.
  2. Calculate the middle index of the list using math.floor((low+high)/2)
  3. Compare the value at the middle index with the target value.
    1. If the target value is equal to the middle value, the search is complete and return the middle index.
    2. If the target value is less than the middle value, set the high pointer to the middle index - 1 and perform the search again.
    3. If the target value is greater than the middle value, set the low pointer to the middle index + 1 and perform the search again.
  4. Repeat steps 2-3 until the target value is found or the low pointer is greater than the high pointer.

If the target value is not found, return -1.

The final value of the low pointer will represent the position of the index in the sorted list.