# Binary Search

Pawan Arora

Ranch Hand

Posts: 105

posted 7 years ago

You'll need to sort the array first. Binary search by definition works only on sorted arrays. This is because of the way it searches for elements:

1) start at the center

2) check the current element

3)

a) if equal then done

b) if smaller then all previous elements are smaller; get the binary search of the second half of the array

c) if larger then all next elements are larger; get the binary search of the first half of the array

In the end the first / second half of the array will be only one element and the recursion can end.

[ November 23, 2008: Message edited by: Rob Prime ]

1) start at the center

2) check the current element

3)

a) if equal then done

b) if smaller then all previous elements are smaller; get the binary search of the second half of the array

c) if larger then all next elements are larger; get the binary search of the first half of the array

In the end the first / second half of the array will be only one element and the recursion can end.

[ November 23, 2008: Message edited by: Rob Prime ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions