Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

MODULE 1

PART A

1. If there are 22,049 data elements being searched, what is the


maximum number of ”looks” it will take with binary search to find
the data element being searched for.

A. At most it will take 15 "looks". The log2(22049) is approximately


14.4.

2. Explain the importance of data structures and discuss typical


algorithm complexities of different problems? Write the best,
average, and worst-case analysis of linear search and binary
search algorithms.

A. Data structure provides the right way to organise information in


the digital space. The data structure is a key component of
Computer Science and is largely used in the areas of Artificial
Intelligence, operating systems, graphics, etc.
The performances of algorithms can be measured on the scales of
Time and Space.

● The Time Complexity of an algorithm or a program is a


function of the running time of the algorithm or a program.
● The Space Complexity of an algorithm or a program is a
function of the space needed by the algorithm or program to
run to completion.

In linear search, best-case complexity is O(1) where the element is


found at the first index. Worst-case complexity is O(n) where the
element found at the last index of the element is not present in the
array and average-case complexity is O(n).
In binary search, best-case complexity is O(1) where the element is
found at the middle index. The worst-case complexity is O(logn).
The average case is O(logn).

3. Suppose an array A with elements indexed 1 to n is to be


searched for a value x. Write pseudo code that performs a
forward search, returning n + 1 if the value is not found.

A. Pseudo Code
4. Searching in a phone book: A phone book is stored in a text file,
containing names of people, their city names and phone numbers.
Choose an appropriate data structure to search a person’s phone
number based on his / her first name and city.
A. Didn’t get it. Please share in #we-code

5. Sorting a phone book: Given a text file containing people’s


names, their city and phone numbers. Write a program which
prints all the city names in an alphabetical order and for each one
of them print their names in alphabetical order and their
corresponding phone number.
A.

phone_dictionary = {}
def PhoneBook(phone_dictionary:dict,name:str,city:str,phoneNo:int):
if(city not in phone_dictionary.keys()):
phone_dictionary[city] = {name:phoneNo}
else:
if(name in phone_dictionary[city].keys()):
print('Person with same name found! Creating a new
duplicate entry! ')
phone_dictionary[city][name+'(duplicate)'] = phoneNo
else:
phone_dictionary[city][name] = phoneNo

ch = 'y'

while(ch.lower() != 'n'):
PhoneBook(phone_dictionary,input('Full Name:
').lower().strip(),input('City Name:
').lower().strip(),int(input('Phone No: ')))
ch = input('Do you want to insert a phone record(y/n):
').strip()

print('Sorted PhoneBook: ')

for records in sorted(phone_dictionary.keys()):


print("City:",records)
for names in sorted(phone_dictionary[records]):
print(names,phone_dictionary[records][names])

6. What is a binary search and write the pseudocode for binary


search.

A. Binary search is a fast search algorithm with run-time complexity


of Ο(log n). This search algorithm works on the principle of divide
and conquer. For this algorithm to work properly, the data collection
should be in sorted form.

Procedure of Binary search


Binary search is implemented using the following steps...
Step 1: Start
Step 2: Input Sorted array in "a[]" and element to be searched
in "x" and size of array in "size"
Step 3: Initialise low=0, high=size-1
Step 4: Repeat until low>=high
Step 4.1: mid=(low+high)/2
Step 4.2: If a[mid] is equal to x,
then, print index value of mid and Goto step 6
Else
If a[mid]<x
low=mid+1
else high=mid-1
Step 5: Print x not found in the list
Stop 6: Stop

7. Given an array A of non-negative integers of size m. Your task is


to sort the array in non-decreasing order and print out the original
indices of the new sorted array.

A. Program

lst = [5,9,7,8,6,2,1]
orig = lst.copy()
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i]<lst[j]:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
print("Sorted list with Original List Index")
for i in range(len(lst)):
print(orig.index(lst[i]), end=' ')

8. Consider the following list of integers:


[12,9,3,14,5,66,7,80,9,10] and arrange the elements in descending
order using insertion sort.
A. Program:

def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i

while j > 0 and key > array[j - 1]:


array[j] = array[j -1]
j = j - 1

array[j] = key

return array

lst = [12,9,3,14,5,66,7,80,9,10]
print(insertion_sort(lst))

9. Consider the following list of integers: [1,9,33,47,5,6,7,80,9,10]


and write the procedure for finding the element ‘7’ using binary
search.

A. Procedure of Binary search


Binary search is implemented using the following steps...
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element
in the sorted list.
Step 4 - If both are matched, then display "Given element is
found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the
search element is smaller or larger than the middle element.
Step 6 - If the search element is smaller than the middle
element, repeat steps 2, 3, 4, and 5 for the left sublist of the
middle element.
Step 7 - If the search element is larger than the middle
element, repeat steps 2, 3, 4, and 5 for the right sublist of the
middle element.
Step 8 - Repeat the same process until we find the search
element in the list or until the sublist contains only one
element.
Step 9 - If that element also doesn't match with the search
element, then display "Element is not found in the list!!!" and
terminate the function.

10. Define insertion sort and write the pseudocode for insertion
sort.

A. Insertion sort is the sorting mechanism where the sorted array is


built having one item at a time. The array elements are compared
with each other sequentially and then arranged simultaneously in
some particular order. The analogy can be understood from the
style of arranging a deck of cards.

Pseudo Code:
n = int(input("Enter the number of elements in the list"))
lst = list(map(int, input("Enter the elements of the list
separated by space").split()))[:n]
for i in range(1,n):
key = lst[i]
j=i-1
while j>0 and key<lst[j]:
lst[j+1] = lst[j]
j-=1
lst[j+1] = key
print("The Sorted List is: ",lst)

PART B

1. What are internal and external sorting techniques? Given an


unsorted array arr[0..n-1] of size n, find the minimum length
subarray arr[s..e] such that sorting this subarray makes the
whole array sorted.

A. Internal Sorting
● Internal sorting is a type of sorting which is used when the
entire collection of data is small enough that sorting can take
place within the main memory. There is no need for external
memory for the execution of sorting programs.
● It is used when the size of the input is small
● Examples:- Bubble sort, insertion sort, quicksort, heapsort
External Sorting
● External sorting is a term for a class of sorting algorithms that
can handle massive amounts of data.
● External sorting is required when the data being sorted do not
fit into the main memory of a computing device (usually RAM)
and instead, they must reside in the slower external memory
(usually a hard drive).
● Examples:- Merge Sort

Finding Unsorted Subarray

def findUnsortedSubarray(nums):
res = sorted(nums)
ans = 0
r = []
for i in range(len(res)):
if nums[i] != res[i]:
r.append(i)
if not len(r):
return 0
if len(r) == 1:
return 1
return r[-1]-r[0]+1
print(findUnsortedSubarray([2,6,4,8,10,9,15]))

2. Define a data structure? Draw and explain the classification of


data structures.
A.
● Data structure is a particular way of storing and organising
data in a computer so that it can be used efficiently.
● It is a special format for organising and storing data.
● Arrays, linked lists, trees, graphs, etc. are all data structures.

3. The Fibonacci numbers are the numbers in the following


integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. . . . . . Write a
function that generates first N Fibonacci numbers

A. Program

def fibonacci(num):
a = 0
b = 1
c = 0
for i in range(num):
print(c, end=' ');
a = b;
b = c;
c = a + b;

num = int(input('Enter how many numbers needed in Fibonacci


series- '))
fibonacci(num)

4. Explain the linear search procedure for the following list of


elements and assume the key element is 96.
List: 12, 23, 34, 45, 55, 62, 71, 85, 96

A. Procedure for Linear Search


Step 1: Select the first element as the current element.
Step 2: Compare the current element with the key element. If
matches, then go to step 5.
Step 3: If there is a next element, then set the current element to
the next element and go to Step 2.
Step 4: Key element not found. Go to Step 6 and Repeat.
Step 5: Key element found and return location.
Step 6: Exit process.

Program

a= [12, 23, 34, 45, 55, 62, 71, 85, 96]


search = 96
c = 0
for i in range(len(a)):
if(search==a[i]):
c+=1
break
if(c==1):
print("Element is present")
else:
print("Element is not present")

5. A Pancake Sorting Problem: Given an unsorted array, sort the


given array. One can do only the following operation on an array.
flip(arr, i): Reverse array from 0 to i Write an efficient program for
sorting a given array in O(nLogn) time on the given machine.

A.

def flip(arr, i):


start = 0
while start < i:
temp = arr[start]
arr[start] = arr[i]
arr[i] = temp
start += 1
i -= 1

# Returns index of the maximum


# element in arr[0..n-1]
def findMax(arr, n):
mi = 0
for i in range(0,n):
if arr[i] > arr[mi]:
mi = i
return mi

# The main function that sorts given array


# using flip operations
def pancakeSort(arr, n):
# Start from the complete array and one by one
# reduce current size by one
curr_size = n
while curr_size > 1:
# Find index of the maximum element in
# arr[0..curr_size-1]
mi = findMax(arr, curr_size)
# Move maximum element to end of current array
# if it's not already at
# the end
if mi != curr_size-1:
# To move at the end,
# first move maximum
# number to beginning
flip(arr, mi)

# Now move the maximum number to end by


# reversing current array
flip(arr, curr_size-1)
curr_size -= 1
# A utility function to print an array of size n
def printArray(arr, n):
for i in range(0,n):
print ("%d"%( arr[i]),end=" ")

# Driver program
arr = [23, 10, 20, 11, 12, 6, 7]
n = len(arr)
pancakeSort(arr, n);
print ("Sorted Array ")
printArray(arr,n)

6. Define sorting? Write the procedure for bubble sort using a


suitable example?

A. Sorting is a process of ordering or placing a list of elements from


a collection in some kind of order. It is nothing but storage of data in
sorted order. Sorting can be done in ascending and descending
order. It arranges the data in a sequence which makes searching
easier.

Procedure for Bubble Sort


Bubble sort is a comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if
they are not in order.
1. Starting with the first element(index = 0), compare the current
element with the next element of the array.
2. If the current element is greater than the next element of the
array, swap them.
3. If the current element is less than the next element, move to
the next element. Repeat Step 1 to check if more swaps are
needed.

n = int(input("Enter the number of elements in the list"))


lst = list(map(int, input("Enter the elements separated by
space").split()))[:n]
for i in range(n):
for j in range(n):
if lst[i]<lst[j]:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
print("The Sorted List is: ",lst)

7. Explain Binary Search procedure for the following list of


elements and assume the key element is 85.
12, 23, 34, 45, 55, 62, 71, 85, 96

A. Procedure of Binary search


Binary search is implemented using the following steps...
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element
in the sorted list.
Step 4 - If both are matched, then display "Given element is
found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the
search element is smaller or larger than the middle element.
Step 6 - If the search element is smaller than the middle
element, repeat steps 2, 3, 4 and 5 for the left sublist of the
middle element.
Step 7 - If the search element is larger than the middle
element, repeat steps 2, 3, 4 and 5 for the right sublist of the
middle element.
Step 8 - Repeat the same process until we find the search
element in the list or until the sublist contains only one
element.
Step 9 - If that element also doesn't match with the search
element, then display "Element is not found in the list!!!" and
terminate the function.

8. Explain the following two comparison sort algorithms with an


example and write their time complexities? Bubble sort &
Selection sort

A.

Bubble sort Selection sort

In bubble sort, two adjacent In selection sort, the minimum


elements are compared. If the element is selected from the
adjacent elements are not at array and swapped with an
the correct position, swapping element which is at the
would be performed. beginning of the unsorted sub
array.

It uses an exchanging method. It uses a selection method.

It is slower than the selection It is faster than the bubble sort


sort as a greater number of as a lesser number of
comparisons is required. comparisons is required.

Bubble Sort Example

n = int(input("Enter the number of elements in the list"))


lst = list(map(int, input("Enter the elements").split()))[:n]
for i in range(n-1):
for j in range(n-1-i):
if lst[j+1]<lst[j]:
lst[j+1], lst[j] = lst[j], lst[j+1]
print("The Sorted List is: ",lst)

Selection Sort Example

n = int(input("Enter the number of elements in the list"))


lst = list(map(int, input("Enter the elements").split()))[:n]
for i in range(n):
index = i
for j in range(i+1,n-1):
if lst[j]<lst[index]:
index = j
lst[i],lst[index] = lst[index],lst[i]
print("The Sorted List is: ",lst)

Time Complexity

Algorithm Best Average Worst

Bubble Sort O(n) O(n2) O(n2)

Selection Sort O(n2) O(n2) O(n2)

9. Consider the following list of integers: [1,9,33,47,5,6,7,80,9,10]


and write the procedure for finding the element ‘7’ using binary
search.

A. Procedure of Binary search


Binary search is implemented using the following steps...
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element
in the sorted list.
Step 4 - If both are matched, then display "Given element is
found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the
search element is smaller or larger than the middle element.
Step 6 - If the search element is smaller than the middle
element, repeat steps 2, 3, 4 and 5 for the left sublist of the
middle element.
Step 7 - If the search element is larger than the middle
element, repeat steps 2, 3, 4 and 5 for the right sublist of the
middle element.
Step 8 - Repeat the same process until we find the search
element in the list or until the sublist contains only one
element.
Step 9 - If that element also doesn't match with the search
element, then display "Element is not found in the list!!!" and
terminate the function.

10. Define insertion sort and write the pseudo code for insertion
sort.

A. Insertion sort is the sorting mechanism where the sorted array is


built having one item at a time. The array elements are compared
with each other sequentially and then arranged simultaneously in
some particular order. The analogy can be understood from the
style of arranging a deck of cards.

Insertion Sort Program:

n = int(input("Enter the number of elements in the list"))


lst = list(map(int, input("Enter the elements").split()))[:n]
for i in range(1,n):
key = lst[i]
j=i-1
while j>=0 and key<lst[j]:
lst[j+1] = lst[j]
j-=1
lst[j+1] = key
print("The Sorted List is: ",lst)

11. Write the name of the sorting technique which is used in


playing card games? Write a procedure for sorting a given list of
numbers using that technique? 14, 25, 36, 74, 85, 6, 53, 62, 41

A. Selection Sort can be used while playing card games.

def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
return A
A=[int(i) for i in input().split(" ")]
x=selectionSort(A)
print(x)

12. Write the algorithm for bubble sort and then explain with an
example

A.
1. Pre: list != fi
2. Post: list is sorted in ascending order for all values
3. for i <- 0 to list:Count - 1
4. for j <- 0 to list:Count - 1
5. if list[i] < list[j]
6. Swap(list[i]; list[j])
7. end if
8. end for
9. end for
10. return list
11. end Bubble_Sort

def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
arr=[int(i) for i in input().split()]
x=bubbleSort(arr)
print(x)

13.Explain the procedure, advantages and disadvantages of linear


and binary search with a suitable example?
A. Procedure of Linear Search

The main disadvantage of a linear search is the fact that it's time
consuming for the enormous arrays.

def linear_search(arr, n):


for i in range(len(arr)):
if arr[i] == n:
return i
return -1
arr = [3, 2, 6, 19, 15, 20]
n = 15
r = linear_search(arr, n)
if(r == -1):
print("Element not found")
else:
print("Element found at index",str(r))

Procedure of Binary search


Binary search is implemented using the following steps...
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element
in the sorted list.
Step 4 - If both are matched, then display "Given element is
found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the
search element is smaller or larger than the middle element.
Step 6 - If the search element is smaller than the middle
element, repeat steps 2, 3, 4 and 5 for the left sublist of the
middle element.
Step 7 - If the search element is larger than the middle
element, repeat steps 2, 3, 4 and 5 for the right sublist of the
middle element.
Step 8 - Repeat the same process until we find the search
element in the list or until the sublist contains only one
element.
Step 9 - If that element also doesn't match with the search
element, then display "Element is not found in the list!!!" and
terminate the function.
Advantages and Disadvantages of Binary Search:
def binarySearch (arr, l, r, x):
if r >= l:
mid = (l + r)//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1

arr=[int(i) for i in input().split()]


l=0
r=len(arr)
x=int(input())
x=binarySearch(arr,l,r,x)
if x==-1:
print("not found")
else:
print("element found at index: ",x)

14. Compare the time complexities of various searching and


sorting algorithms?

A. TABLE BELOW
15. Write an algorithm to search for an employee ID in an array

A.
1. Read the employee ID to be searched
2. Set i = 0
3. Repeat step 4 until i > n or arr[i] = employee ID
4. Increment i by 1
5. If i > n:
Display “Not Found”
Else
Display “Found”

16. Explain bubble sort by sorting the following list of elements:


5 ,1, 4, 2, 8.
A. Bubble Sort Algorithm is used to arrange N elements in
ascending order, and for that, you have to begin with the 0th
element and compare it with the first element.
If the 0th element is found greater than the 1st element, then the
swapping operation will be performed, i.e., the two values will get
interchanged. In this way, all the elements of the array get
compared.

def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

arr=[5,1,4,2,8]
x=bubbleSort(arr)
print(x)

17. What is the idea behind Selection sort and sort the following
list of elements using that idea. array A = [ 7 , 5 , 4 , 2 ] needs to be
sorted in ascending order.

A. The Algorithm is mentioned below:


1. Get a list of unsorted numbers
2. Set a marker for the unsorted section at the front of the list
3. Repeat steps 4 - 6 until one number remains in the unsorted
section
4. Compare all unsorted numbers in order to select the smallest
one
5. Swap this number with the first number in the unsorted
section
6. Advance the marker to the right one position
7. Stop

def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
return A

A=[7,5,4,2]
x=selectionSort(A)
print(x)

18. Sort the given list of elements using selection sort.


14, 33,27,10,35,19,42,4

def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
return A

A=[14, 33,27,10,35,19,42,4]
x=selectionSort(A)
print(x)

19. Define selection sort and write pseudo code for selection sort

A. Selection sort is a simple sorting algorithm. This sorting algorithm


is an in-place comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left end and the
unsorted part at the right end. Initially, the sorted part is empty and
the unsorted part is the entire list.

The smallest element is selected from the unsorted array and


swapped with the leftmost element, and that element becomes a
part of the sorted array. This process continues moving the
unsorted array boundary by one element to the right.

def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]

20. Explain insertion sort with an example and compare time


complexity of insertion sort with other sorting algorithms.

A.
Example:

def insertionSort(nlist):
for index in range(1,len(nlist)):

currentvalue = nlist[index]
position = index

while position>0 and nlist[position-1]>currentvalue:


nlist[position]=nlist[position-1]
position = position-1

nlist[position]=currentvalue

nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)

Output:
[14, 21, 27, 41, 43, 45, 46, 57, 70]

PART C

1. Define Data Structure? Draw the diagram showing classification


of data structures?

A.
● Data structure is a particular way of storing and organising
data in a computer so that it can be used efficiently.
● It is a special format for organising and storing data.
● Arrays, linked lists, trees, graphs, etc. are all data structures.
2. Define Recursion? Give examples for linear and non-linear
recursion?

A. The process in which a function calls itself directly or indirectly is


called recursion and the corresponding function is called a recursive
function.

Linear Recursion Function for Factorial of a Number

def get_factorial_recursively(n):
if n <= 1:
return 1
else:
return n * get_factorial_recursively(n-1)

Non Linear Recursion Function for Fibonacci Sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

3. Consider a situation where swap operation is very costly. State


the name of the sorting algorithm which should be preferred
among the following sorting algorithms - Bubble sort, Insertion
sort, Selection sort, Merge sort, Quicksort

A. Selection sort makes O(n) swaps which is minimum among all


sorting algorithms mentioned above.

4. Define an algorithm? Write the properties of algorithms?

A. Algorithm is a step-by-step procedure, which defines a set of


instructions to be executed in a certain order to get the desired
output. The properties are mentioned below:
1. Input: There are more quantities that are extremely supplied.
2. Output: At least one quantity is produced.
3. Definiteness: Each instruction of the algorithm should be clear
and unambiguous.
4. Finiteness: The process should be terminated after a finite
number of steps.
5. Effectiveness: Every instruction must be basic enough to be
carried out theoretically or by using paper and pencil.
5. List the area of applications of Data Structures?

A. They are used in the areas of


★ Compiler Design
★ Operating System
★ DBMS
★ Graphics
★ Simulation
★ Numerical Analysis
★ Artificial Intelligence

6. You have to sort 1 GB of data with only 100 MB of available main


memory. Which sorting technique will be most appropriate among
the following sorting algorithms- Bubble sort, Insertion sort,
Selection sort, Merge sort, Quicksort

A. The data can be sorted using external sorting which uses


merging technique. This can be done as follows:
1. Divide the data into 10 groups each of size 100.
2. Sort each group and write them to disk.
3. Load 10 items from each group into the main memory.
4. Output the smallest item from the main memory to disk. Load
the next item from the group whose item was chosen.
5. Loop step #4 until all items are not outputted.

The steps 3-5 come under Merge Sort Technique.

7. Which data structure is used to perform recursion?


A. Stack. Because of its LIFO (Last In First Out) property it
remembers its ‘caller’ so it knows whom to return when the function
has to return. Recursion makes use of system stack for storing the
return addresses of the function calls. Every recursive function has
its equivalent iterative (non-recursive) function.

8. What are the practical algorithm design issues?

A. Practical Algorithm Design Issues:


1. To save time (Time Complexity): A program that runs faster is
a better program.
2. To save space (Space Complexity): A program that saves
space over a competing program is considerably desirable.

9. Write the disadvantage of linear search compared to other


searching techniques?

A. The Disadvantages of Linear Search are as follows:


1. In linear search it needs more space and time complexity.
2. In linear search if the key element is the last element and the
search is from the first element that is a worst case, or if the
key element is the first element and the search is from the last
element then also it is the worst case.

10. Given a list arr = 2, 5, 7, 55, 72, key = 72, write the procedure
for finding the element 72 using linear search?
A. Procedure for Linear Search:
Step 1: Select the first element as the current element.
Step 2: Compare the current element with the target element. If
matches, then go to step 5.
Step 3: If there is a next element, then set the current element to
the next element and go to Step 2.
Step 4: Target element not found. Go to Step 6.
Step 5: Target element found and return location.
Step 6: Exit process.

11. Explain time and space complexity of an algorithm?


A.
● The performances of algorithms can be measured on the
scales of Time and Space.
● The Time Complexity of an algorithm or a program is a
function of the running time of the algorithm or a program.
● The Space Complexity of an algorithm or a program is a
function of the space needed by the algorithm or program to
run to completion.

12. Write any two applications of binary search?


● This algorithm is used to search elements in a given sorted
array with more efficiency.
● It could also be used for a few other additional operations like-
to find the smallest element in the array or to find the largest
element in the array.
13. State the name of the sorting algorithm will take least time
when all elements of the input array are identical by considering
typical implementations of sorting algorithms.

A. Insertion sort

14. State the name of the sorting algorithm which is least


dependent on the initial ordering of the input?

A. In Insertion sort if the array is already sorted then it takes O(n)


and if it is reverse sorted then it takes O(n2) to sort the array.

15. Define a linked list and write any two advantages of linked
lists.

A. Linked list is a linear data structure, in which the elements are not
stored at contiguous memory locations.

Advantages of Linked List:

Dynamic data structure: A linked list is a dynamic arrangement so it


can grow and shrink at runtime by allocating and deallocating
memory. So there is no need to give the initial size of the linked list.
No memory wastage: In the Linked list, efficient memory utilisation
can be achieved since the size of the linked list increases or
decreases at run time so there is no memory wastage and there is
no need to pre-allocate the memory.

Implementation: Linear data structures like stack and queues are


often easily implemented using a linked list.

Insertion and Deletion Operations: Insertion and deletion


operations are quite easier in the linked list. There is no need to
shift elements after the insertion or deletion of an element; only the
address present in the next pointer needs to be updated.

16. Define Big-Oh, Big-Omega and Theta notations?


A.
● Omega notation is used to represent best time complexity
● Big-Oh notation is used to represent worst time complexity
● Theta notation is used to represent average time complexity

17. Consider a list arr = 1, 2, 4, 3. Bubble sort is used to sort the


elements of a list. Find out the number of iterations that will be
required to sort the list?

A. Even though the first two elements are already sorted, bubble
sort needs 4 iterations to sort the given array.
18. Write the best, average and worst case time complexities of
selection sort?

Algorithm Best Average Worst

Selection Sort O(n2) O(n2) O(n2)

19. Write the worst case time complexity of bubble sort when the
input array is already sorted?
A. O(n)

20. Write the best, average and worst case time complexities of
insertion sort?

Algorithm Best Average Worst

Insertion Sort O(n) O(n2) O(n2)

You might also like