Professional Documents
Culture Documents
Data Structures Module 1 QB Complete Solutions
Data Structures Module 1 QB Complete Solutions
PART A
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
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()
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=' ')
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i
array[j] = key
return array
lst = [12,9,3,14,5,66,7,80,9,10]
print(insertion_sort(lst))
10. Define insertion sort and write the pseudocode for insertion
sort.
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
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
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]))
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;
Program
A.
# Driver program
arr = [23, 10, 20, 11, 12, 6, 7]
n = len(arr)
pancakeSort(arr, n);
print ("Sorted Array ")
printArray(arr,n)
A.
Time Complexity
10. Define insertion sort and write the pseudo code for insertion
sort.
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)
The main disadvantage of a linear search is the fact that it's time
consuming for the enormous arrays.
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”
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.
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)
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
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]
A.
Example:
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
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
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?
def get_factorial_recursively(n):
if n <= 1:
return 1
else:
return n * get_factorial_recursively(n-1)
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
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.
A. Insertion sort
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.
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?
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?