J2-1 Module9

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Binary Search

Data set: 5, 10, 30, 60, 80, 90, 100, 120

Int [] array = {5, 10, 30, 60, 80, 90, 100, 120}

Length of this array = 8

Int low=0

Int high=8-1=7

Searching for 5 in the array:


Value=5

Low=0

High=7

Condition low should be less than or equal to high

Mid= (0+7)/2=3 ----------------------------------------> low=0, high=7

Array [3] =60 and is greater than 5 so high=mid-1=2

Mid= (0+2)/2=1 ----------------------------------------> low=0, high=2

Array [1] = 10 and is greater than 5 so high=mid-1=0

Array [0] = 5 and is equal to 5 so 5 is there in the array

Comparisons: 2

Searching for 20 in the array:


Value=20

High=7

Low=0

Condition is low should be less than or equal to high

Mid = (0+7)/2=3 ----------------------------------------> low=0, high=7

Array [3] =60 and is less than 20 so high=mid-1=2;


Mid = (0+2)/2=1 ----------------------------------------> low=0, high=2

Array [1] = 10 and is less than 20 so low=mid+1=2

Mid = (2+2)/2=2 ----------------------------------------> low=2, high=2

Array [2] = 30 and is greater than 20 so 20 is not found the array

Comparisons: 3

You might also like