0% found this document useful (0 votes)
7 views

LAB2 - Python

The document describes implementing and analyzing recursive and iterative linear search algorithms. It provides pseudocode for recursive and iterative linear search and Python programs to implement the algorithms. The objectives are to code the algorithms and analyze their complexity for different input sizes.

Uploaded by

abdulmjeedbasllo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

LAB2 - Python

The document describes implementing and analyzing recursive and iterative linear search algorithms. It provides pseudocode for recursive and iterative linear search and Python programs to implement the algorithms. The objectives are to code the algorithms and analyze their complexity for different input sizes.

Uploaded by

abdulmjeedbasllo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Lab Manual (Design and Analysis of Algorithm)

Experiment # 2
Recursive and Iterative Linear Search Lab Instructor: Eng Kamal Al-homidi

Objectives:
• Implement Recursive and Iterative Linear Search.
• Determine the complexity of the algorithms.
• Repeat the experiment for different values of n, the number of elements in the list to be
searched.

Algorithm #a: Recursive Linear Search


RecLinearSearch (n, A, k)
// n – number of elements in the array
// A – array of numbers
// k – the key to be searched
if n < 0 return -1;
if k == a[n-1] return (n-1);
else
return RecLinearSearch(n-1,A,k);

Algorithm #b: Iterative Linear Search


IterLinearSearch(A, n, key)
// A – Array of elements
// n – size of an array
// key – element to be searched
for i = 1 to n
if A[i] = key then return i
else return -1

Program #a: in Python


// Recursive Linear Search
def recursive_linear_search(n, arr, k):
if n == 0:
return -1
elif k == arr[n - 1]:
return (n - 1)
else:
return recursive_linear_search(n - 1, arr, k)

n = int(input("Enter the Size of Array: "))


arr = []
for i in range(n):
arr.append(int(input(f"Enter Element In array [{i}]: ")))

k = int(input("Enter Number to Search in Array: "))

pos = recursive_linear_search(n, arr, k)


if pos == -1:
print(f"The element {k} is not found in the array.")
else:
print(f"The element {k} is found at index [{pos}] of the given
array.")

OutPut:

Program #b: in Python


Write a full Program for Iterative Linear Search using the next pseudo code

Pseudo Code Iterative Linear Search

IterLinearSearch(A, n, key)
// A – Array of elements
// n – size of an array
// key – element to be searched
for i = 1 to n
if A[i] = key then return i
else return -1

You might also like