Data Structure and Algorithm W4
Data Structure and Algorithm W4
ALGORITHMS
2
3
4
5
6
# Element to Find x = 'J’
7
Binary Search Algorithm is a searching
algorithm used in a sorted array
by repeatedly dividing the search
interval in half. The idea of binary
search is to use the information that the
array is sorted and reduce the time
complexity to O(log N).
8
To apply Binary Search algorithm:
9
Below is the step-by-step algorithm for
Binary Search:
•Divide the search space into two halves
by finding the middle index “mid”.
•Compare the middle element of the
search space with the key.
•If the key is found at middle element, the
process is terminated.
10
•If the key is not found at middle element,
choose which half will be used as the next
search space.
• If the key is smaller than the middle element,
then the left side is used for next search.
• If the key is larger than the middle element,
then the right side is used for next search.
•This process is continued until the key is
found or the total search space is exhausted.
11
To understand the working of
binary search, consider the
following illustration:
Consider an array arr[] = {2, 5, 8,
12, 16, 23, 38, 56, 72, 91}, and
the target = 23.
12
13
14
15
16
17
Given a sorted array of n
uniformly distributed values
arr[], write a function to
search for a particular
element x in the array.
18
1D Interpolation
The function interp1d() is used to
interpolate a distribution with 1
variable.
It takes x and y points and
returns a callable function that
can be called with new x and
returns corresponding y.
19
from scipy.interpolate import interp1d
import numpy as np
xs = np.arange(20)
ys = 1*xs + 2
print(newarr)
20
21
Spline
Interpolation
22
In 1D interpolation the points
are fitted for a single
curve whereas in Spline
interpolation the points are fitted
against a piecewise function
defined with polynomials called
splines.
23
The UnivariateSpline()
function
takes xs and ys and
produce a callable
funciton that can be
called with new xs.
24
from scipy.interpolate import UnivariateSpline
import numpy as np
xs = np.arange(10)
ys = xs**2 + np.sin(xs) + 1
print(newarr)
25
26