The binary search algorithm is used to obtain the index of a given number by dividing the search bound in half over iteration. If the value entered in the array a message pop up telling that ''value is not present in the array". Please see the code. 
 

restart; with(ArrayTools); AA := Array(1 .. 10, [20, 2, 30, 4, 50, 7, 60, 8, 90, 100]); AA := sort(AA); KEYVALUE := 200; DUP_KEYVALUE := infinity; low := 1; high := NumElems(AA); while DUP_KEYVALUE <> KEYVALUE do mid := floor((low+high)*(1/2)); if AA[mid] = KEYVALUE then DUP_KEYVALUE := KEYVALUE; printf("%s\n %a\n", "the index is ", mid) elif AA[mid] < KEYVALUE then low := mid+1 elif AA[mid] > KEYVALUE then high := mid-1 end if; if low > high then printf("%s\n", "value not present in the array"); break end if end do


 

Download BINARY_SEARCH1.mw

 


Please Wait...