Topic 9 - Search Algorithms
Topic 9 - Search Algorithms
Algorithms
WMSU
• check if the Item we’re searching for is Equal to Mid (key == mid)
We assign mid
New+Low1 as=the
5 NEW low
• If not, then we check:
And again find Mida New
= 5 +mid
(9 –using
5) / 2the formula:
– If our key is Less than Mid (key < mid) then set Mid – 1 as the NEW High
mid = lowMid+ (high
= 7 - low) / 2
– If our key is Greater than Mid (key > mid) then set Mid + 1 as the NEW Low
New High = 6
Mid = 5 + (6 – 5) / 2
Mid = 5 + ½
Mid = 5
Binary Search
Binary Search
MyArray ← sorted array
n ← size of array
key ← value to be searched
lowerBound = 0
upperBound = n – 1 #Note that Arrays start at 0, so the size of array should be n - 1
compute midPoint = lowerBound + ( upperBound - lowerBound ) / 2 #Our formula for finding mid
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midpoint
Interpolation Search
• The Interpolation Search is an improvement over Binary
Search for instances, where the values in a sorted array
are uniformly distributed.
• It just uses a different formula for finding the midpoint
• Interpolation search may go to different locations
according to the value of the key being searched.
• Formula is instead:
mid = low + ((x – A[low]) * (high – low) / (A[high] – A[low]))
Interpolation Search
• Step1: In a loop, calculate the value of “pos” using the
probe position formula.
• Step2: If it is a match, return the index of the item, and exit.
• Step3: If the item is less than arr[pos], calculate the probe
position of the left sub-array. Otherwise, calculate the same
in the right sub-array.
• Step4: Repeat until a match is found or the sub-array
reduces to zero.