(Kim starts watching the live feed on his TV.)
(Soldiers bow toward Kim, bringing the seven suspected tourists onto the TV screen.)
Kim: It's time to find out who the culprit (target) is.
Soldier 1: Absolutely, Supreme Leader! But these 7 tourists (elements) are of different ages.
Kim: Line them up from the smallest age to the largest (indexes 0 to 6). I'll find the target (culprint) . It's fun!
(Kim starts laughing, staring at the TV.)
(Soldiers sorted the tourists by age in ascending order and tied up their hands)
Tourist 5 (shouting): What mistake have we made? Please let us know!
Soldier 2: One of you tried to sell japanese manga here; it's illegal.
Soldier 3: (bows toward Kim) Supreme Leader! Our secret agency reports his age as 43.
Soldier 2: We found him, Supreme Leader! Let me shoot him.
Kim: Wait. It's my order. I was busy testing missiles for a while. I missed playing with people. Let me guess and find him.
(The seven tourists stand with fear in their eyes. The actual tourists' ages in sorted are: array = [21, 25, 29, 32, 37, 43, 50]. Start = 21, end = 50. mid = 32)
Kim: Let me start with the middle one (mid, index 3). Tell me your age, you there.
Tourist 4 (shouts): 32, Supreme Leader!
(43 > 32, target > mid, target is on the right of mid. because elements are in ascending order , so leave the elements on left of mid including mid)
Kim: Oh no! Soldiers, should I have to release tourists from 1 to 4 (index 0 to 3)?
Soldiers (Bow): Yes, Supreme Leader!
Kim (smiles): You lucky ones, return to your country. Hope you won't get shot.
(Tourists 1 to 4, index (0 to 3), run away. Tourists 5 to 7 remain, index (4 to 6).)
(Tourists remaining: [37, 43, 50], new start = mid + 1 = 37, new mid = 43, end = 50.)
Kim: Hahaha, one of you is going to meet my father up above the sky. Book an appointment.
Kim: Let me choose the middle one again (mid, index 5), tourist 6. Tell me your age, lucky charm.
Tourist 6: Supreme Leader, I'm 43. Please don't kill me.
(In this case, target = mid, that's the answer.that is index = 5)
Kim: Soldiers, aim at the target and shoot him.
(All of a sudden, N.korea lost power supply in the city. The soldiers left the target and let him run away.)
("Kim succeeded in finding the answer using binary search, but due to a power outage, he missed shooting the tourist.")
The tourists safely returned to their countries.
The next day, Kim shot all the soldiers and their families for allowing the tourists to escape.
Things to be observed
Chances: no tourist of age 43 found (condition start> end = no element found)
Best case : finding the target at the very first chance that is middle (middle element = answer) time complexity is o(1)
Best way to find mid : kim: (start +end)/2
us : start + (end - start)/2
Both are same
Code:
Output: index: 5