The code below searches an unsorted array, .4, for a given value. It returns the
ID: 3669689 • Letter: T
Question
The code below searches an unsorted array, .4, for a given value. It returns the index of the value if it is present. Otherwise it returns -1. Suppose before we call linearSearch we randomly permute (i.e., reorder) the elements in A. In the following problem, we will find the expected asymptotic runtime of linearSearch. What is the best case asymptotic runtime of linearSearch on an array of n elements? What index must val be located at to elicit this runtime? What is the worst case asymptotic runtime of linearSearch on an array of n elements? What index must val be located at to elicit this runtime? Let X_j be the random variable which, given an permutation of the elements in our array, is 1 if index A[j] will be checked in our linearSearch for that permutation and 0 otherwise. What is the expected value of X_j? Let X be the random variable which, given an permutation of the elements in our array, is the number of elements of A which will be checked in our linearSearch for that permutation. Define X using n copies of the random variable defined in the previous step. Compute the expected value of A' for using the linearity of expectation. Given this, what is the expected asymptotic runtime of linearSearch?Explanation / Answer
3) E(x) = 1/n
4)
Since the probability of X = A[i] is 1/n for all i = 1, . . . , n, and we need to check exactly i elements when X = A[i], we have that expected value of the number of checks is (1/n)*(1 + 2 + · · · + n) = (1/n)* n*(n + 1)/2 = (n + 1)/ 2 .
5). In the worst case it is O(n). The avarage case running time is c · (n+1)/ 2 = (n) since for all n 1 we have 1(/2)*n ( n+1)/2 n.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.