0% found this document useful (0 votes)
28 views10 pages

Unit 5

Uploaded by

guptakrishns23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views10 pages

Unit 5

Uploaded by

guptakrishns23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

[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

Linear search searches all items and its worst execution


time is n where n is the number of items.

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

Interpolation search requires items to be in sorted order


but its worst execution time is O(n) where n is the
number of items and it is much faster than linear
search.

Search in Python
Searching is a technique to find the particular element is
present or not in the given list.

There are two types of searching -

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.

What is a Linear Search?


Linear search is a method of finding elements within a
list. It is also called a sequential search. It is the Linear Search Algorithm
simplest searching algorithm because it searches the
desired element in a sequential manner. There is list of n elements and key value to be searched.

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

Concept of Linear Search Program

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):

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 1


[Unit 5]

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)

Binary Search in Python


Binary Search is a searching algorithm for finding an
element's position in a sorted array. In this approach,
the element is always searched in the middle of a
portion of an array. Binary search can be implemented
only on a sorted list of items. If the elements are not
sorted already, we need to sort them first.

The binary search tree is a balanced binary search tree.


Height of the binary search tree becomes log(n). So,

Time complexity of BST Operations = O(logn).


We can find the element position using the following
methods.
o Recursive Method
o Iterative Method

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 2


[Unit 5]
Repeat until the number that we are searching for is found. array = [3, 4, 5, 6, 7, 8, 9]
x=4

result = binarySearch(array, x, 0, len(array)-1)


Python Implementation if result != -1:
print("Element is present at index " + str(result))
Iteration Method else:
print("Not found")
do until the pointers low and high meet each other.
mid = (low + high)/2 The complexity of the binary search algorithm is O(1) for the
best case.
if (x == arr[mid])
return mid This happen if the element that element we are looking find in
else if (x > arr[mid]) // x is on the right side the first comparison. The O(logn) is the worst and the average
low = mid + 1 case complexity of the binary search.
else // x is on the left side
high = mid – 1 Sorting Algorithms
Sorting is the processing of arranging the data in
Recursive Method ascending and descending order. There are several
Binary_Search (arr, x, low, high) types of sorting in data structures namely – bubble sort,
if low > high insertion sort, selection sort, bucket sort, heap sort,
return False quick sort, radix sort etc.
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x > arr[mid] // x is on the right side
return Binary_Search(arr, x, mid + 1, high)
else // x is on the right side
return Binary_Search(arr, x, low, mid - 1)

# Binary Search in python

def binarySearch(array, x, low, high):

# Repeat until the pointers low and high meet each other
while low <= high:

mid = low + (high - low)//2

if array[mid] == x:
return mid

elif array[mid] < x:


low = mid + 1

else:
high = mid - 1

return -1 Below we see five such implementations of sorting in


python.

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 3


[Unit 5]

 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

# Checking if any element was left


while i < len(L):
arr[k] = L[i]
i += 1
k += 1

while j < len(R):


arr[k] = R[j]
j += 1
k += 1

# Code to print the list

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]

# into 2 halves Output


R = arr[mid:] Given array is
[By.- Prof. Narendra Kumar_CSE@9560549827] Page 4
[Unit 5]

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.

Working of Selection Sort


1. Set the first element as minimum.

2. Select first element as minimum


3. Compare minimum with the second element. If
the second element is smaller than minimum, assign the
second element as minimum.

Compare minimum with the third element. Again, if the


third element is smaller, then assign minimum to the
third element otherwise do nothing. The process goes on
until the last element.

8. The first iteration

4. Compare minimum with the remaining elements


5. After each iteration, minimum is placed in the
front of the unsorted list.

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 5


[Unit 5]

# to sort in descending order, change > to < in this


9. The second iteration
line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx],
array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

Fibonacci sequence Using Recursion


10. The third iteration Fibonacci sequence:

A Fibonacci sequence is a sequence of integers which first two


terms are 0 and 1 and all other terms of the sequence are
obtained by adding their preceding two numbers.

For example: 0, 1, 1, 2, 3, 5, 8, 13 and so on….

# Python program to display the Fibonacci sequence

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

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 6


[Unit 5]

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;

Tower of Hanoi Puzzle Using Python if ( nDisks == 1 )


{
Tower of Hanoi, is a mathematical puzzle which /* ----------------------------------------------------
consists of three towers (pegs) and more than one rings Solving a trivial (base case) Tower of Hanoi
is as depicted − these rings are of different sizes and problem:
stacked upon in an ascending order, i.e. the smaller one
sits over the larger one.

----------------------------------------------------
-- */
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.

 No larger disk may be placed on top of a smaller


disk.
------------------------------------------------ */
Pseudo code:
tower(disk, source, inter, dest) /* ------------------------------------------------
Determine the helpPeg
IF disk is equal 1, THEN ------------------------------------------------ */
move disk from source to destination helpPeg = peg index that is not equal to from
ELSE Peg and toPeg;
tower(disk - 1, source, destination, intermediate)
// Step 1 /* ---------------------------------------------------
move disk from source to destination // First: solve this smaller Tower of Hanoi problem:
Step 2
tower(disk - 1, intermediate, source, destination)
// Step 3
END IF
END

---------------------------------------------------- */

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 7


[Unit 5]

sol1 = hanoi( nDisks-1, fromPeg, helpPeg ); print ("Sorted array is:")


// Sol1 looks like: 1 -> 3, 1 -> 2, ... for i in range(n):
print (arr[i],end=" ")
/* ---------------------------------------------------
Output:
Next: do this move
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
---------------------------------------------------- */
myStep = "Do this move: fromPeg --> toPeg";
Merge list
/* --------------------------------------------------- We can use the append() method to merge a list into another.
Finally: solve this smaller Tower of Hanoi problem: The append() method is used to append new elements to an
existing list. To merge two lists using the append() method,
we will take a list and add elements from another list to the
list one by one using a for loop.

# List of strings

list_1 = ["This", "is", "a", "sample", "program"]


# List of ints
---------------------------------------------------- */ list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
sol2 = hanoi( nDisks-1, helpPeg, toPeg );
// Sol2 looks like: 1 -> 3, 1 -> 2, .. # Iterate over a list and add elements to another list
for elem in list_2:
/*====================================== list_1.append(elem)
How to use the solutions sol1 and sol2 to print('Extended List:')
print(list_1)
solve hanoi(nDisks, fromPeg, toPeg):
1. first making the moves in sol1 Output:
2. then do myStep
3. finally, do the moves in sol2 Extended List:
======================================*/ ['This', 'is', 'a', 'sample', 'program', 10, 2, 45, 3, 5, 7, 8, 10]
mySol = so1l + myStep + sol2;
// mySol looks like: 1 -> 3, 1 -> 2, ... Higher order sort
return ( mySol );
} A higher-order function can be defined as a function that
accepts one or more functions as arguments and returns a
# tower of hanoi function as a result. In this article, we will discuss some swift
def TowerOfHanoi(n , from_rod, to_rod, aux_rod): higher-order functions, including for Each, map, Compact
if n == 1: Map, flat Map, filter, reduce, sort, and sorted.
print ("Move disk 1 from rod",from_rod,"to rod",to_rod)
return We must have basic knowledge of the following concepts:
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print ("Move disk",n,"from rod",from_rod,"to rod",to_rod) 1. Python functions
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 2. Parameters
# main 3. Python objects
n=3 4. Python decorators
TowerOfHanoi(n, 'A', 'C', 'B')
# A, B, C are the rod

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 8


[Unit 5]

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.

What is recursive method? # Python3 program to find factorial of given number

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);

# ----- Iteration -----


# Method to find the factorial of a given number

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));

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 9


[Unit 5]

print("Factorial of",num,"using Iteration is:",

factorialUsingIteration(5));

Difference between Recursion and Iteration

Property Recursion Iteration

Function calls A set of instructions


Definition itself. repeatedly executed.

Application For functions. For loops.

Through base When the


case, where termination
there will be condition for the
no function iterator ceases to be
Termination call. satisfied.

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.

Very Relatively lower


high(generally time
exponential) complexity(generally
Time time polynomial-
Complexity complexity. logarithmic).

[By.- Prof. Narendra Kumar_CSE@9560549827] Page 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy