Ask Your Question
1

How can one obtain the position of an index in a sorted list without utilizing any pre-existing functions?

asked 2023-06-09 17:31:23 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-09 17:57:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-09 17:31:23 +0000

Seen: 13 times

Last updated: Jun 09 '23