Initially low = 0, high = n-1
n = 1000, So, high = 999
x = 501
1)while (0 <= 999) ---------------true
m = (0 + 999)/2 = 499
if(501 > a[m]), i.e. if (501 > a[499] )i.e. if (501 > 500) ----------true [1st comparison]
low = 499 + 1 = 500
- while(500 < = 999) -----------------true
m = (500 + 999)/2 = 749
if(501 > 749 ) --------------false [2nd comparison]
elseif(501 < 749) ---------true [3rd comparison]
high = 749 – 1 = 748
- while (500 <= 748) ----------------true
m = (500 + 748)/ 2 = 624
if (501 > 624) ------------false [4th comparison]
elseif(501 < 624) -------------true [5th comparison]
high = 624 -1 = 623
- while (500 < = 623) ---------------true
m = (500 + 623)/2 = 581
if(501 > 581) -------------false [6th comparison]
elseif( 501 < 581)--------------true [7th comparison]
high = 581 - 1 = 580
- while (500 < = 580) ---------true
m = (500 + 580)/ 2 = 540
if ( 501 > 540)---------false [8th comparison]
else if (501 < 540) --------------true [9th comparsion]
high = 539
- while (500<= 539) -----------true
m = (500 + 539)/2 = 519
if (501 > 519) ---------------false [10th comparison]
elseif (501 < 519) ----------------true [11th comparison]
high = 519 - 1 = 518
- while (500 < = 518) --------------true
m = (500 + 518)/ 2 = 509
if( 501 > 509 ) ---------------false [12th comparison]
elseif( 501 < 509) --------------true [13th comparison]
high = 509 – 1 = 508
- while(500 <= 508) -----------true
m = (500 + 508)/2 = 504
if(501 > 504)------------false [14th comparison]
elseif(501 < 504 ) ----------true [15th comparison]
high = 503
- while (500 <= 503) ---------------true
m = (500 + 503)/2 = 501
if(501 > 501) ----------false [16th comparison]
elseif( 501 < 501 )----------false [17th comparison]
else part will be executed and it will return m i.e. location where the required element is present.
So, total 17 comparisons are required in this case.