0% found this document useful (0 votes)
18 views5 pages

Linear and Binary Search

Uploaded by

Mal Eficent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Linear and Binary Search

Uploaded by

Mal Eficent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

AS & A LEVEL COMPUTER SCIENCE 9618

LINEAR SEARCHING

In this each element of an array is checked from lower bound to upper bound until
the item is found or the upper bound is reached.
PSEUDOCODE
Consider an array StudentNames containing 10 student names.

FOR Counter = 1 TO 10
isFound = FALSE
INPUT NameToSearch
IF StudentNames[Counter] = NameToSearch
THEN
isFound = TRUE
OUTPUT “Located at position: ” & Counter
ENDIF
NEXT

1 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618

BINARY SEARCHING
If there are 10240 elements in an array, then to search specific value will require
10240 comparisons.
Binary search can do the same task in less time and less comparisons
Note: Array needs to be sorted before a binary search is done

1 2 3 4 5 6 7 8 9 10 Positions
4 8 15 20 47 60 65 74 85 90 Elements
Qtn: Print “Present ” if 60 is in the array
Case1: Data is at mid position
Case 2: Data < value at mid position
Case3: Data > Value at mid position
Note:
Is 60 > 47 : If yes then the values from 1 till 5th element are not required (
Because the required value is greater than mid value, then we consider the
greater part)

2 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618

BINARY SEARCHING
If the value required is > Mid value then
LowerBound = MidPoint +1
If the value required is < mid value then
UpperBound = MidPoint -1

PSEUDOCODE
UpperBound = 10
LowerBound = 1
isFound = FALSE
NotInList = FALSE
ValueToSearch

3 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618

BINARY SEARCHING
WHILE isFound = FALSE AND NotInList = FALSE
INPUT ValueToSearch
MidPoint = (UpperBound + LowerBound) \ 2
IF Numbers[MidPoint] = ValueToSearch
THEN
isFound = TRUE
ELSE
IF Numbers[MidPoint] > ValueToSearch
THEN
LowerBound = MidPoint -1
ELSE
UpperBound = MidPoint + 1
ENDIF
IF LowerBound > UpperBound
THEN
NotInList = TRUE
ENDIF
ENDIF
ENDWHILE

4 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618

BINARY SEARCHING

WHY AN ARRAY NEED TO BE SORTED BEFORE A BINARY SEARCH IS USED


It does not check every value
The middle element is the middle element not the numeric value
When the higher or lower elements are discarded there will not be higher or
lower elements
It might discard the value you looking for

5 Davis_Kazibwe@2023KIS

You might also like