Is it possible to do a binary search on an unordered list, and if so, what would the code look like? Thank you very much for the help.
Asked
Active
Viewed 68 times
0
-
1Does this answer your question? [Binary search in a Python list](https://stackoverflow.com/questions/38346013/binary-search-in-a-python-list) – Vivs Nov 15 '22 at 14:43
-
1No, you can't. The basic logic of binary search requires a sorted list. – John Coleman Nov 15 '22 at 14:44
-
1No dear. It is not possible. It has be sorted. Otherwise, the logic will fail to search the element as binary search checks the mid values and then proceed ahead in either of direction assuming it is sorted. – Nish Nov 15 '22 at 14:44
1 Answers
2
Read this Binary Search.
In the second line it says
"...is a search algorithm that finds the position of a target value within a sorted array."
If we have the following list: lst = [1, 3, 4, 6, 2, 9, 8, 5, 7]
, and we want to find where 6
is.
We would look at the element in the middle of the list. In this case 2
, the algorithm checks to see if 2 < 6
and that is in fact true. The algorithm would now search for 6
in the right sub-list, i.e. [9, 8, 5, 7]
because it assumes a sorted list and it will not be able to find our target 6
.
So in short, you can not do binary search on an unordered list.

mudi loodi
- 103
- 5