Back to the 2023 paper

Module 1: Introduction

20237m

Apply the Linear Search algorithm to find the position of the target element 7 in the following array: A=[3,5,2,8,7,1,4]A=[3, 5, 2, 8, 7, 1, 4]. Also, analyze the time and space complexity.

Worked SolutionAI Assisted

Linear Search for 7 in A=[3,5,2,8,7,1,4]A=[3,5,2,8,7,1,4]

Algorithm

LinearSearch(A, n, key):
  for i=0 to n-1:
    if A[i]==key: return i  // 0-based index, +1 for 1-based position
  return -1 // not found

Trace for key=7

i (0-based) A[i] Compare A[i]==7? Action
0 3 3==7? No continue
1 5 5==7? No continue
2 2 2==7? No continue
3 8 8==7? No continue
4 7 7==7? Yes return 4 (0-based) / 5 (1-based)
Search stops early; elements after index4 not examined.

Result: Found at index 4 (0-based) → position 5 (1-based). Comparisons = 5 best/worst?

Complexity Analysis (n=7n=7)

  • Time:
    • Best O(1)O(1) (key at first position)
    • Worst O(n)O(n) (key absent or at last) → here worst would be 7 comparisons
    • Average O(n)O(n) → expected (n+1)/2(n+1)/2 if key present uniformly
    • In this instance 5 comparisons = Θ(n)\Theta(n) worst-like.
  • Space: O(1)O(1) auxiliary (loop variable + key), O(n)O(n) total if counting input array; in-place.
  • No sorting needed; works on unsorted arrays; optimal for unsorted (any algorithm must examine Ω(n)\Omega(n) in worst case).

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.