Documente Academic
Documente Profesional
Documente Cultură
Average u
Search
For unsorted array probability of occuring an element at any position in the array will be 1/n.
Example:Consider an array A[5,3,4,2,1]
Case 1:
1->5 comparisons
2->4 comparisons
3->2 comparisons
4->3 comparisons
5->1 comparisons
Searching Element 1
Probability of 1 occuring in any position is 1/5
Cases:a)If 1 is at first place A[1] number of comparison 1/5*1
b)If 1 is at the second place A[2] number of comparisons 1/5*2
c)If 1 is at the last position A[5]number of comparisons 1/5*5
Average number of comparisons=(1/5)(1+2+3+4+5)=3comparison/number
Derivation
Now o side a a a )[ ]
Case1:Searching first element for example 5.
This 5 can occur at any position in the array.So probability of 5 occuring in any of the n locations will be
1/n.
Cases (Finding first element 5)
1.Element 5 is at first location=1/n*1
2. Element 5 is at the second location=1/n*2
.
.
.
n. Element 5 is at the n th location =1/n*n
E pe ted u e of o pa iso s= + + +
Number of Cases=n
Average numbe of comparisons needed to find element 5 will be=
/ * + / * + / * +.+ / *
= /
+ + +.+
=(1/n)(n*(n+1)/2)
=(n+1)/2 [Ignore as constant ]
Approximately we require n/2 average comparisons to find any element(named T) in unsorted array
using linear search .
to -1
A[n/2] is middle term and to find this element we require only 1 comparison i.e A[n/2]
Similarly consider the following
A[(n/4] or A[3n/4]-> will require 2 comparisons i.e A[n/2] and A[n/4] or A[n/2] A[3n/4].
.
.
.
A[ ],A[ ],.A[ ] will e ui e log n o pa iso s i.e A[ / ],A[ / ],A[ / ],..,A[ ] .
We have found that using 1 comparison we can found only 1 element. Using 2 comparisons we
can get 2 values. After 3 comparisons we can find 4 elements. Therefore we can say after k
comparisons we can find 2^(k-1) elements
Expected number of comparisons
=[ * ^ + * ^ ++k* ^ k-1)]
This above equation is AGP(Arithemetic and geomatric)Series and can be written in log form
=(k-1)2^k+1
Soultion of above series is taken from below example
Example
S= + * + * ^ + * ^ +. * ^ +
* ^
Therefore
2S=2+2*2^2+ * ^ +.
* ^
Now subtracting 2S-S we get
=[100(2^100)]-[ ^ + ^ ++ ^ + + ]
Above series is GP
=[100*2^100]-(1-2^100)/(1-2)
=100*2^100-2^100-1
=99*2^100+1
Therefore total number of comparisons
=nlogn
Cases=n
Therefore Average comparison for binary search will be logn.