Binary Search
Binary search is a more complex algorithm than linear search and requires all items to be in order/ sort
The algorithm runs as follows:
- Sort the list item and than start by setting the counter to the middle position in the list.
- If the value held there is a match, the search ends.
- If the value at the midpoint is less than the value to be found, the list is divided in half, the lower half of the list is ignored and the search keeps to the upper half of the list.
- Otherwise, if the value at the midpoint is greater than the value to be found, the upper half of the list is ignored and the search keeps to the lower half of the list.
- The search moves to the midpoint of the remaining items. Steps 2 through 4 continue until a match is made or there are no more items to be found.
In
Find <-- 7 Found <-- False Start <-- 0 End <-- length(list) WHILE Found = False AND Start <= End Mid <-- (Start + End) DIV 2 IF list[Mid] = Find THEN OUTPUT 'Found at' + Mid Found <-- True ELSE IF List[Mid] > Find THEN End <-- Mid - 1 ELSE Start <-- Mid + 1 ENDIF ENDIF ENDWHILE IF Found = False THEN OUTPUT 'Not found' ENDIF
.