Unit 5
Unit 5
Step - 1: Start the search from the first element and Check key =
Search Techniques 7 with each element of list x.
Linear Search
Binary Search Step - 2: If element is found, return the index position of the
key.
Binary search requires items to be in sorted order but
its worst execution time is constant and is much faster
than linear search.
Interpolation Search
Search in Python
Searching is a technique to find the particular element is
present or not in the given list.
o Linear Search
o Binary Search Step - 3: If element is not found, return element is not present.
Both techniques are widely used to search an element in
the given list.
1. Linear_Search(list, key)
It compares each and every element with the value that
2. for each item in the list
we are searching for. If both are matched, the element is 3. if item == value
found, and the algorithm returns the key's index 4. return its index position
position. 5. return -1
Let's understand the following steps to find the element key = 7 def linear_Search(list1, n, key):
in the given list. # Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key): The divide and conquer approach technique is followed by the
return i recursive method. In this method, a function is called itself
return -1 again and again until it found an element in the list.
list1 = [1 ,3, 5, 4, 7, 9] We have a sorted list of elements, and we are looking for the
key = 7 index position of 45.
n = len(list1)
res = linear_Search(list1, n, key) [12, 24, 32, 39, 45, 50, 54]
if(res == -1):
print("Element not found") So, we are setting two pointers in our list. One pointer is used to
else: denote the smaller value called low and the second pointer is
used to denote the highest value called high.
print("Element found at index: ", res)
Next, we calculate the value of the middle element in the array.
Output:
1. mid = (low+high)/2
Element found at index: 4
2. Here, the low is 0 and the high is 7.
Explanation:
3. mid = (0+7)/2
In the above code, we have created a
function linear_Search(), which takes three arguments - 4. mid = 3 (Integer)
list1, length of the list, and number to search. We
Now, we will compare the searched element to the mid index
defined for loop and iterate each element and compare value. In this case, 32 is not equal to 45. So we need to do
to the key value. If element is found, return the index further comparison to find the element.
else return -1 which means element is not present in the
list. If the number we are searching equal to the mid. Then
return mid otherwise move to the further comparison.
Linear Search Complexity The number to be search is greater than the middle number, we
compare the n with the middle element of the elements on the
Time complexity of linear search algorithm - right side of mid and set low to low = mid + 1.
o Base Case - O(1) Otherwise, compare the n with the middle element of the
o Average Case - O(n) elements on the left side of mid and set high to high = mid - 1.
o Worst Case -O(n)
# Repeat until the pointers low and high meet each other
while low <= high:
if array[mid] == x:
return mid
else:
high = mid - 1
Bubble Sort
Merge Sort # Sorting the first half
Insertion Sort mergeSort(L)
Shell Sort
Selection Sort # Sorting the second half
mergeSort(R)
Merge Sort
i=j=k=0
Merge sort is a sorting technique based on divide and
conquer technique. With worst-case time complexity # Copy data to temp arrays L[] and R[]
being Ο(n log n), it is one of the most respected while i < len(L) and j < len(R):
algorithms. if L[i] < R[j]:
arr[k] = L[i]
First, divide the list into the smallest unit (1 element), i += 1
then compare each element with the adjacent list to sort else:
and merge the two adjacent lists. Finally, all the arr[k] = R[j]
elements are sorted and merged. j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
# Python program for implementation of MergeSort if __name__ == '__main__':
def mergeSort(arr): arr = [12, 11, 13, 5, 6, 7]
if len(arr) > 1: print("Given array is", end="\n")
printList(arr)
# Finding the mid of the array mergeSort(arr)
mid = len(arr)//2 print("Sorted array is: ", end="\n")
printList(arr)
# Dividing the array elements
L = arr[:mid]
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Selection Sort
In selection sorting algorithm is an in-place 6. Swap the first with minimum
comparison-based algorithm in which the list is divided 7. For each iteration, indexing starts from the first
into two parts, the sorted part at the left end and the unsorted element. Step 1 to 3 are repeated until all the
unsorted part at the right end. Initially, the sorted part elements are placed at their correct positions.
is empty and the unsorted part is the entire list.
def fibonacci(n):
if(n <= 1):
return n
else:
Then we repeat the process for each of the remaining return(fibonacci(n-1) + fibonacci(n-2))
elements in the unsorted list. n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
Algorithm of Selection Sort- for i in range(n):
print(fibonacci(i))
selectionSort(array, size) Output
repeat (size - 1) times Enter number of terms: 10
set the first unsorted element as the minimum Fibonacci sequence:
for each of the unsorted elements 0 1 1 2 3 5 8 13 21 34
if element < currentMinimum
set element as new minimum
Program Explanation
swap minimum with first unsorted position
end selectionSort
1. User must enter the number of terms and store it
# Selection sort in Python in a variable.
2. The number is passed as an argument to a
def selectionSort(array, size): recursive function.
3. The base condition is that the number has to be
for step in range(size): lesser than or equal to 1.
min_idx = step 4. Otherwise the function is called recursively with
for i in range(step + 1, size): the argument as the number minus 1 added to
the function called recursively with the argument String hanoi( int nDisks, int fromPeg, int toPeg )
as the number minus 2. {
5. The result is returned and a for statement is used
to print the fibonacci series. int helpPeg;
----------------------------------------------------
-- */
return( "Do this move: fromPeg --> toPeg" );
}
We need to transfer all the disks to the final rod else
under the given constraints− {
/* ------------------------------------------------
Only one disk can be moved at a time. Solving a non-trivial Tower of Hanoi problem:
Each move consists of taking the upper disk
from one of the stacks and placing it on top of
another stack.
A disk can only be moved if it is the uppermost
disk on a stack.
---------------------------------------------------- */
# List of strings
Sorted Function number times all of the numbers below it up to and including
1.
The sorted function simply sorts a given sequence in a For example, factorial(5) is the same as 5*4*3*2*1 , and
specific order. (either in ascending order or in descending factorial(3) is 3*2*1 .
order)
Syntax :- Iterative Method
sorted(sequence, key (optional), reverse(optional))
An iterative method is a mathematical procedure that uses
Note :- There is a basic difference between sort() and sorted() an initial value to generate a sequence of improving
function in Python. The difference is that the sort() function approximate solutions for a class of problems, in which
doesn’t return any value but in the case of sorted() function, the n-th approximation is derived from the previous ones.
it returns an iterable list. Or The process of attempting for solving a problem which
finds successive approximations for solution, starting
#declaring string from an initial guess. The result of repeated calculations is a
str = "codespeedy" sequence of approximate values for the quantities of interest.
#calling sorted function
result = sorted(str) # sorting string A major advantage of iterative methods is that round off
#displaying result errors are not given a chance to “accumulate,” as they are
print(result) in Gaussian Elimination and the Gauss-Jordan Method,
because each iteration essentially creates a new
Output : ['c', 'd', 'd', 'e', 'e', 'e', 'o', 'p', 's', 'y'] approximation to the solution.
A method or algorithm that repeats steps by using one or # ----- Recursion -----
more loops. # Method to find factorial of given number
Recursive: A method or algorithm that invokes itself one
or more times with different arguments. def factorialUsingRecursion(n):
Base case: A condition that causes a recursive method not to if (n == 0):
make another recursive call.
return 1;
# recursion call
return n * factorialUsingRecursion(n - 1);
def factorialUsingIteration(n):
res = 1;
# using iteration
for i in range(2, n + 1):
res *= i;
return res;
Recursion in data structure is when a function calls itself
indirectly or directly, and the function calling itself is # Driver method
known as a recursive function. num = 5;
It's generally used when the answer to a larger issue could be
print("Factorial of",num,"using Recursion is:",
depicted in terms of smaller problems.
Example of recursive programming involves computing
factorials. The factorial of a number is computed as that factorialUsingRecursion(5));
factorialUsingIteration(5));
Used when
code size
needs to be Used when time
small, and complexity needs to
time be balanced against
complexity is an expanded code
Usage not an issue. size.
Smaller code
Code Size size Larger Code Size.