0% found this document useful (0 votes)
2 views2 pages

Binary Search 2

dsa

Uploaded by

vaidyapranjali9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Binary Search 2

dsa

Uploaded by

vaidyapranjali9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

03 October 2024 14:22

[0] [1] [2] [3] [4] [5] [6] [7] [8]


Key = 33
11 22 33 44 55 66 77 88 99
left mid right
Left sub-Array Right Sub- Array

1) Get the key from the user.

2) Calculate As 33 is smaller to 55,


Left = 0 Continue search in Left sub Array
Right = 8
Mid = (L+R) / 2 [0] [1] [2] [3]
=4 11 22 33 44

Left mid right


3) Compare the key with the mid element.
a. If key matches, return the index 2) Left = 0
b. Else, go to step 4 Right = mid-1 = 3
33 == 55 ? no Mid = (L+R) / 2
=1
4) Check if the key is smaller to mid element or
greater. 3) Compare key with mid element
If smaller, search in left sub array 33 == arr[mid]
Left Sub array is from left to mid-1 33 == 22 ? No
Go to step 4
If Greater, then search in Right Sub-array
Right sub-Array is from mid+1 to right 4) Check if key is smaller or greater to
mid element
As key is greater, continue the search
in Right sub array

[2] [3]
Right Sub-Array
33 44

Left right
mid

2) Left = mid + 1
=2
Right = 3
Mid = (L+R) / 2
=2

3) Compare the key with the mid element


33 == arr[mid]
Binary_Search_2 Page 1
33 == arr[mid]
Yes, key found at index 2

Binary_Search_2 Page 2

You might also like