0% found this document useful (0 votes)
6 views185 pages

UNIT-I

The document provides a comprehensive overview of data structures, particularly focusing on their definitions, classifications, and applications in Python. It emphasizes the importance of data structures in efficient data management and algorithm design, detailing various types such as arrays, stacks, queues, and linked lists. Additionally, it discusses the differences between primitive and non-primitive data structures, as well as the advantages and disadvantages of using arrays.

Uploaded by

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

UNIT-I

The document provides a comprehensive overview of data structures, particularly focusing on their definitions, classifications, and applications in Python. It emphasizes the importance of data structures in efficient data management and algorithm design, detailing various types such as arrays, stacks, queues, and linked lists. Additionally, it discusses the differences between primitive and non-primitive data structures, as well as the advantages and disadvantages of using arrays.

Uploaded by

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

Data Structures and Its Applications

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
UNIT – I
Data Structures:
Introduction, Difference between data type and data structure, Need of Data
structure, Classification of Data structures, Linear vs. Non-linear Data Structures.
Types of Data Structures in Python:
Built-in and User-defined data structures.
Static Linear Data Structure: Arrays-
Characteristics of an Array, Applications of Arrays. Arrays vs. List.
Searching:
Linear Search, Binary search.
Sorting:
Merge Sort, Bubble Sort, Selection Sort and Quick Sort

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 2Department Freshman Engineering
Introduction
What is Data?
The quantities, characters or symbols on which operations are performed by a
computer, which may be stored or transmitted in the form of electrical signal
or recorded on magnetic, optical or mechanical recording media.

DataInformation ?

I am a Students-------Information(Processed Data)
aymnemsiaryus ------------------Data
To provide appropriate way to structure the data, Data Structures is required.

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 3Department Freshman Engineering
Introduction(contnd…)
What is Data Structure?
A data structure is a way of organizing and storing data in a
computer so that it can be accessed and used efficiently.
 The main idea behind using data structures is to minimize the time
and space complexities.
 An efficient data structure takes minimum memory space and
requires minimum time to execute the data.

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 4Department Freshman Engineering
Introduction(contnd…)
 Data Structures are the main part of many Computer
Science Algorithms as they allow the programmers to
manage the data in an effective way.
 It plays a crucial role in improving the performance of a
program or software, as the main objective of the
software is to store and retrieve the user's data as fast
as possible.

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 5Department Freshman Engineering
Need of Data Structure
As applications are becoming more complex and the
amount of data is increasing every day,
which may lead to problems with
1.data searching,
2.processing speed,
3.multiple requests handling and many more.
 Data Structures support different methods to organize,
manage, and store data efficiently.
 With the help of Data Structures, we can easily traverse
the data items.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 6Department Freshman Engineering
Need of Data Structure

Eg.
Student rollnumber in 20000 pages pdf.
Case:1: all the numbers are arranged at random.
Case:2: all the numbers are arranged in an ascending order

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 7Department Freshman Engineering
Need of Data Structure
1.Efficient data processing: Data structures provide a
way to organize and store data in a way that allows for
efficient retrieval, manipulation, and storage of data.
2.Memory management: Proper use of data structures
can help to reduce memory usage and optimize the use
of resources. For example, using dynamic arrays can
allow for more efficient use of memory than using static
arrays.

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 8Department Freshman Engineering
Need of Data Structure
3. Code reusability: Data structures can be used as
building blocks in various algorithms and programs,
making it easier to reuse code.
4. Abstraction: Data structures provide a level of
abstraction that allows programmers to focus on the
logical structure of the data and the operations that can
be performed on it, rather than on the details of how the
data is stored and manipulated.
5. Algorithm design: Many algorithms rely on specific
data structures to operate efficiently. Understanding data
structures is crucial for designing and implementing
efficient
Data algorithms.
Structures using
06/13/2025
Python Dr. P. Praveen Kumar 9Department Freshman Engineering
Why should we learn Data
Structures?
1. Data Structures and Algorithms are two of the key
aspects of Computer Science.
2. Data Structures allow us to organize and store data,
whereas Algorithms allow us to process that data
meaningfully.
3. Learning Data Structures and Algorithms will help us
become better Programmers.
4. We will be able to write code that is more effective and
reliable.
5. We will also be able to solve problems more quickly
Data
and efficiently
Structures using Python
06/13/2025
Dr. P. Praveen Kumar 10
Department Freshman Engineering
Applications:
 2D Arrays image Processing, Sudoku, Chess.
 Stack  redo, undo, browsing history, call history
 Queue Circular queue-switch bw apps,FCFS, printer que.
 Linked list previous page, next page (browser)
 Double LL music player(previous song, next song), gallery(prev.img,next img)
 Graphfb, linkedin, social networking sites(users),fb graph api, googles
knowledge api, google maps, yahoo and apple maps uses graphs to
show the shortest path using BFS algo.
 Tree Representation file structure in File explorer, auto suggestion,
decision based ML.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 11
Department Freshman Engineering
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 12
Department Freshman Engineering
Data type Data structure
A data type is a classification of A Data structure is a collection of
data that defines the type of value data of similar or different data
that a variable can hold. In other types. This collection of data can be
words, it is a way to specify the represented using an object and
data type that a variable can store. can be used throughout the
program.
The implementation of data type is The implementation of data
known as an abstract structure is known as a concrete
implementation. implementation.
It can hold value but not data. It can hold multiple types of data
Therefore, we can say that it is within a single object.
data-less.
In case of data type, a value can be In the case of data structure, some
assigned directly to the variables. operations are used to assign the
data to the data structure object.
`There is no problem in the time When we deal with a data structure
complexity. object, time complexity plays an
Data Structures using Python
06/13/2025 important
Dr. P. Praveen Kumar role. 13
Department Freshman Engineering
Classification of data structures

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 14
Department Freshman Engineering
Classification of data structures
Data Structures are normally divided into two broad
categories:

(1) Primitive Data Structures

(2) Non-Primitive Data Structures

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 15
Department Freshman Engineering
Classification of data structures
Primitive Data Structures

 Primitive Data Structures are the data structures consisting of the


numbers and the characters that come in-built into programs.
 These data structures can be manipulated or operated directly by
machine-level instructions.

Ex: Integer, Float, Character, and Boolean etc.


 These data types are also called Simple data types, as they contain
characters that can't be divided further.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 16
Department Freshman Engineering
Classification of data structures
Non-Primitive Data Structures
 Non-Primitive Data Structures are the complex data structures
which are derived from Primitive Data Structures.
 These data structures can't be manipulated or operated directly by
machine-level instructions.
 The focus of these data structures is on forming a set of data
elements that is either homogeneous (same data type) or
heterogeneous (different data types).

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 17
Department Freshman Engineering
Non-Primitive Data Structures
 The choice of data structure depends on the problem to be solved
and the operations to be performed on the data.
 Different data structures have different strengths and weaknesses
and are suitable for different scenarios.
 Understanding the different types of data structures and their
characteristics is important for efficient algorithm design and
implementation.

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 18
Department Freshman Engineering
Non-Primitive Data Structures

Based on the structure and arrangement of data, data structures


are divided into two sub-categories -
1. Linear Data Structures
2. Non-Linear Data Structures

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 19
Department Freshman Engineering
Non-Primitive Data Structures
Linear Data Structures:
 A data structure that preserves a linear connection among its
data elements is known as a Linear Data Structure.
 The arrangement of the data is done linearly, where each
element consists of unique successors and predecessors
except the first and the last data element.
 However, it is not necessarily true in the case of memory, as
the arrangement may not be sequential.
 Linear data structures are one-dimensional and can be
traversed sequentially from the first to the last element.
Ex: Arrays, lists, stack, queue, etc.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 20
Department Freshman Engineering
Non-Primitive Data Structures
Based on memory allocation, the Linear Data Structures
are further classified into two types:
1. Static Data Structure
2. Dynamic Data Structure

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 21
Department Freshman Engineering
Linear Data Structures
Static Data Structures:
The data structures having a fixed size are known as
Static Data Structures. The memory for these data
structures is allocated at the compiler time, and their size
cannot be changed by the user after being compiled;
However, the data stored in them can be altered.
The Array is the best example of the Static Data
Structure as they have a fixed size, and its data can be
modified later.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 22
Department Freshman Engineering
Static Linear Data Structures

• An array is a collection of items stored at contiguous memory locations

• The idea is to store multiple items of the same type together


• Arrays are used to store multiple values in one single variable
• Arrays can be multidimensional, and all elements in an array need to be of the same type, all integers
or all floats
• A user can treat lists as arrays.
• Most of the data structures make use of arrays to implement their algorithms. Following are the
important terms to understand the concept of Array.
• Element− Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is used to identify the
element.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Array Representation
• Arrays can be declared in various ways in different languages. Below is an illustration.

• As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Static Linear Data
Structures(Contd…)
Arrays can be classified into different types:

One-Dimensional Array: An Array with only one row of data elements


is known as a One-Dimensional Array. It is stored in ascending storage
location.
Two-Dimensional Array: An Array consisting of multiple rows and
columns of data elements is called a Two-Dimensional Array. It is also
known as a Matrix.
Multidimensional Array: We can define Multidimensional Array as an
Array of Arrays. Multidimensional Arrays are not bounded to two indices
or two dimensions as they can include as many indices are per the
need.
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar 25
Department Freshman Engineering
Arrays
Basic Operations
Following are the basic operations supported by an array.
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Advantages
• In an array, accessing an element is very easy by using the index number.
• The search process can be applied to an array easily
• 2D Array is used to represent matrices
• For any reason a user wishes to store multiple values of similar type then the Array
can be used and utilized efficiently

Disadvantages
• Array size is fixed
• Array is homogeneous - only one type of value can be store in the array (eg..int)
• Array is Contiguous blocks of memory
• Insertion and deletion are not easy in Array
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• Python Lists Vs array Module as Arrays
• We can treat lists as arrays. However, we cannot constrain the type of elements stored in a list.
• For example:
a = [1, 3.5, "Hello"]

• If you create arrays using array module, all elements of the array must be of the same numeric type.
• import array as arr
• a = arr.array('d', [1, 3.5, "Hello"]) // Error

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Creating an Array
• Array is created in Python by importing array module to the python program.
• Then the array is declared as shown below.
from array import *
arrayName = array(typecode, [Initializers])
or
import array
arrayName = array.array(type code, [array,items])

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• Array Syntax
1. Identifier: specify a name like usually, you do for variables
2. Module: Python has a special module for creating array in Python, called "array" – you must import
it before using it
3. Method: the array module has a method for initializing the array. It takes two arguments, type
code, and elements.
4. Type Code: specify the data type using the type codes available (see list below)
5. Elements: specify the array elements within the square brackets, for example [130,450,103]

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Minimum size in
Type code C Type Python Type
• Typecode are the codes that are used to bytes

define the type of value the array will hold. 'b' signed char int 1

Some common typecodes used are 'B' unsigned char int 1

'u' Py_UNICODE Unicode character 2

'h' signed short int 2

'H' unsigned short int 2

'i' signed int int 2

'I' unsigned int int 2

'l' signed long int 4

'L' unsigned long int 4

'f' float float 4

'd' double float 8


Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Creating Array
lets create and print an array using python.
from array import *
array1 = array('i', [10,20,30,40,50]) #array method
for x in array1:
print(x)

Accessing Array Element


• We can access each element of an array using the index of the element.
• The below code shows how
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Insertion Operation
• Insert operation is to insert one or more data elements into an array.
• Based on the requirement, a new element can be added at the beginning, end, or any given index of
array.
• Here, we add a data element at the middle of the array using the python in-built insert() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60) # arrayName.insert(index, value)
for x in array1:
print(x)

append() is also used to add the value mentioned in its arguments at the end of the array.
array1.append(70)
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• We can add one item to a list using append() method or add several items using extend()method.

import array as arr


numbers = arr.array('i', [1, 2, 3])
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array


numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• We can concatenate two arrays using + operator.

import array as arr

odd = arr.array('i', [1, 3, 5])


even = arr.array('i', [2, 4, 6])

numbers = arr.array('i') # creating empty array of integer


numbers = odd + even

print(numbers)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Deletion Operation
• Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
• Here, we remove a data element at the middle of the array using the python in-built remove() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40) #You can also use the 'del' statement of Python. Del array1[index]
for x in array1:
print(x)
Error arises if element doesn’t exist in the set
pop() function can also be used to remove and return an element from the array, but by default it
removes only the last element of the array, to remove element from a specific position of the array,
index of the element is passed as an argument to the pop() method.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Deletion Operation
• We can delete one or more items from an array using Python's del statement.

import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2] # removing third element


print(number) # Output: array('i', [1, 2, 3, 4])

del number # deleting entire array


print(number) # Error: array is not defined

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Search Operation
• You can perform a search for an array element based on its value or its index.
• Here, we search a data element using the python in-built index() method.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))

it produces the following result which shows the index of the element.
If the value is not present in the array then the program returns an error.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Update Operation
• Update operation refers to updating an existing element from the array at a given index.
• Here, we simply reassign a new value to the desired index we want to update.
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• How to change or add elements?
• Arrays are mutable; their elements can be changed in a similar way like lists.
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing first element
numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• Slicing of a Array
• There are multiple ways to print the whole array with all the elements, but to print a specific range of
elements from the array, we use Slice operation.

• Slice operation is performed on array with the use of colon(:).


• To print elements from beginning to a range use [:Index]
• to print elements from end use [:-Index]
• to print elements from specific Index till the end use [Index:]
• to print elements within a range, use [Start Index:End Index] and
• to print whole List with the use of slicing operation, use [:].
• Further, to print whole array in reverse order, use [::-1].

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]


numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Types of arrays
•One dimensional
•Two Dimensional
•Multi Dimensional

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Two dimensional array is an array within an array.
It is an array of arrays.
In this type of array the position of an data element is referred by two indices instead of one.

Consider the example of recording temperatures 4 times a day, every day.


Some times the recording instrument may be faulty and we fail to record data.
Day 1 - 11 12 5 2
from array import *
Day 2 - 15 6 10 T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5],
[12,15,8,6]]
Day 3 - 10 8 12 5
print(T[0])
Day 4 - 12 15 8 6 print(T[1][2])

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• To print out the entire two dimensional array we can use python for loop as shown below.
• We use end of line to print out the values in different rows.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
for r in T:
for c in r:
print(c,end = " ")
print()
Inserting Values in Two Dimensional Array
T.insert(2, [0,5,11,13,6])
Updating Values in Two Dimensional Array
T[2] = [11,9] T[0][3] = 7

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
Here are few more examples related to Python matrices using nested lists.

Add two matrix


# iterate through rows
X = [[12,7,3],
[4 ,5,6],
for i in range(len(X)):
[7 ,8,9]] # iterate through columns
for j in range(len(X[0])):
Y = [[5,8,1],
result[i][j] = X[i][j] + Y[i][j]
[6,7,3],
[4,5,9]]
for r in result:
result = [[0,0,0], print(r)
[0,0,0],
[0,0,0]]

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• # Program to transpose a matrix using nested loop

X = [[12,7], [4 ,5], [3 ,8]]


result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Arrays
• # Program to multiply two matrices using nested loops

# 3x3 matrix # iterate through rows of X


for i in range(len(X)):
X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # iterate through columns of Y
for j in range(len(Y[0])):
# 3x4 matrix # iterate through rows of Y
for k in range(len(Y)):
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
result[i][j] += X[i][k] * Y[k][j]

# result is 3x4 for r in result:


print(r)
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
SEARCHING
Types of Searching
 Unordered Linear Search
 Sorted/Ordered Linear Search
 Binary Search

SORTING Techniques
classifying sorting algorithms
Internal Sort
External Sort

Types of Sortings
Bubble Sort
Insertion Sort
Selection Sort
Merge Sort
Quick Sort
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Searching
What is Searching?
• In computer science, searching is the process of finding an item with specified properties from a
collection of items.
• The items may be stored as records in a database, simple data elements in arrays, text in files, nodes
in trees, vertices and edges in graphs, or they may be elements of other search spaces.

• Why do we need Searching?


• We know that today’s computers store a lot of information. To retrieve this information proficiently
we need very efficient searching algorithms.
• There are certain ways of organizing the data that improves the searching process.
• That means, if we keep the data in proper order, it is easy to search the required element.
• Sorting and Searching is one of the techniques for making the elements ordered.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Searching
Types of Searching
Following are the types of searches.
• Unordered Linear Search
• Sorted/Ordered Linear Search
• Binary Search
• Symbol Tables and Hashing
• String Searching Algorithms: Tries, Ternary Search and Suffix Trees

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Searching
• A search traverses the collection until
– The desired element is found
– Or the collection is exhausted

• If the collection is ordered, I might not have to look at all elements


– I can stop looking when I know the element cannot be in the collection.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
S e a rc h in g

In te re n a l s e a rc h in g E x te rn a l s e a rc h in g

B tre e s e a rc h in g

B + tre e s e a rc h in g

S e a rc h w ith k e y -c o m p a ris o n S e a rc h w ith o u t k e y -c o m p a ris o n

A d re s s c a lc u la tio n s e a rc h

L in e a r s e a rc h N o n -lin e ra s e a rc h

S e q u e n tia l s e a rc h T re e s e a rc h

B in a ry s e a rc h B in a ry s e a rc h tre e

In te rp o la tio n s e a rc h A V L tre e s e a rc h

R e d -b la c k tre e s e a rc h

S p la y tre e s e a rc h

D ig ita l s e a rc h

M u lti-w a y tre e s e a rc h

m -w a y tre e s e a rc h

B -tre e s e a rc h

G ra p h s e a rc h

D e p th firs t s e a rc h

B re a d th firs t s e a rc h

54
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search

55
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6

my_array
7 12 5 22 13 32
target = 13 1 2 3 4 5 6

Target data found

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
Unordered Linear Search
• Let us assume we are given an array where the order of the elements is not known.
• That means the elements of the array are not sorted.
• In this case, to search for an element we have to scan the complete array and see if the element is
there in the given list or not.
def UnOrderedLinearSearch (numbersList, value):
for i in range(len(numbersList)):
if numbersList[i] == value:
return i
return -1

A= [534,246,933,127,277,321,454,565,220]
print(UnOrderedLinearSearch(A,277))

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Flowchart: Sequential Search with Array
Start

i=0

Yes No
K = A[i]?

i = i+1

No
Print "Successful" i≥n
Yes

Print "Unsuccessful"

Stop

59
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
def UnOrderedLinearSearch (numbersList, value):
for i in range(len(numbersList)):
if numbersList[i] == value:
return i
return -1

A=[534,246,933,127,277,321,454,565,220]
print("The elements are:", A)
key=int(input("Enter the element to be searched:"))
status=UnOrderedLinearSearch(A,key)
if(status!=-1):
print("Element found at %i location" %status)
else:
print("Element not found in the list")

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
Sorted/Ordered Linear Search
• If the elements of the array are already sorted, then in many cases we don't have to scan the complete
array to see if the element is there in the given array or not.
• In the algorithm below, it can be seen that, at any point if the value at A[i] is greater than the data to be
searched, then we just return - 1 without searching the remaining array.
def OrderedLinearSearch (numbersList, value):
for i in range(len(numbersList)):
if numbersList[i] == value:
return i
elif numbersList[i] > value:
return
return – 1
• A= [34,46,93,127,277,321,454,565,1220]
• print(OrderedLinearSearch(A,565))

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
Worst Case:
Linear Search Analysis: Worst Case N comparisons

Worst Case: match with the last item (or no match)

7 12 5 22 13 32
target = 32

Linear Search Analysis: Best Case Best Case:


1 comparison
Best Case: match with the first item

7 12 5 22 13 32
target = 7

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Complexity Analysis

• Case 1: The key matches with the first element


• T(n) = 1
• Case 2: Key does not exist
• T(n) = n
• Case 3: The key is present at any location in the array
n
T ( n)  p
i 1
i i

n 1
1 p1  p 2 pi p n 
T ( n) 
n
i
i 1
n

n 1
T ( n) 
2

63
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Complexity Analysis : Summary

Number of key Asymptotic


Case Remark
comparisons complexity

Case 1 T(n) = 1 T(n) = O(1) Best case

Case 2 T(n) = n T(n) = O(n) Worst case

Case 3 n 1 T(n) = O(n) Average case


T ( n) 
2

64
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search

• Of course we could use our simpler search and traverse the array

• But we can use the fact that the array is sorted to our advantage

• This will allow us to reduce the number of comparisons

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search
Built in Functions
A=[534,246,933,127,277,321,454,565,220]
A=[534,246,933,127,277,321,454,56
print("The elements are:", A)
5,220]
key=int(input("Enter the element to be searched:"))
try: print("The elements are:", A)
status=A.index(key) key=int(input("Enter the element to
print("Element found at",status,"location") be searched:"))
except: status=A.count (key)
print("Element not found in the list")
if(status!=0):
print("Element found
at",status,"location")
else:
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search

67
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search
• Let us consider the problem of searching a word in a dictionary.
• Typically, we directly go to some approximate page [say, middle page] and start searching from that point.
• If the name that we are searching is the same then the search is complete.
• If the page is before the selected pages then apply the same process for the first half;
• otherwise apply the some process to the second half.

• Binary search also works in the same way.


• The algorithm applying such a strategy is referred to as binary search algorithm.

• Requires a sorted array or a binary search tree.


• Cuts the “search space” in half each time.
• Keeps cutting the search space in half until the target is found or has exhausted the all possible locations.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Example:

Let the elements of array are - Step 3:

Step 1:
Let the element to search is, K = 56
We have to use the below formula to calculate the mid of the array –
mid = (beg + end)/2
beg = 0
end = 8
mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.

Step 2: Step 4:

Now, the element to search is found. So algorithm will


return the index of the element matched.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
The Technique

m id
m id

l l u m= idm id
= -1
l(l+
= um)/2
id + 1 uu
S erach this half the sam e w ay S erach th is h alf th e sam e w ay
if K < A [m id] if K > A [m id ]

(c ) S(a)
e(ba rc
)AShneathrde ered
o rch e nthtireenlist
e arraytiretuolist
frnelem
s tuinrntonsets
thinetowseith
tha ercinsea
hdinexrch
g voin
f grig
alu o fhl,t-h
es uaan
lf dalf
left-h o nmlyoidn ly

Data Structures using Python


06/13/2025
Dr. P. Praveen Kumar 70
Department Freshman Engineering
Flowchart: Binary Search with Array
Start

mid = (l+u)/2

YES NO
K = A[mid]?

YES NO
K < A[mid]?

Search is successful
u = mid-1 l = mid+1

Stop
NO
(l>u)?

YES

Search is unsuccessful

Start
71
Data Structures using Python
06/13/2025
Dr. P. Praveen Kumar Department Freshman Engineering
Algorithm Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is the index of the first
array element, 'upper_bound' is the index of the last array element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
There are two methods to implement the binary search algorithm –

1. Iterative method

2. Recursive method

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search Algorithm: Program

#Iterative Binary Search Algorithm

def BinarySearchIterative(numbersList, value):


low = 0 A =[534,246,933,127,277,321,454,565,220]
high = len(numbersList)-1 key=int(input("Enter the element to be searched:"))
while low <= high:
mid =(low+high)//2 status=BinarySearchIterative(A,key)
if numbersList[mid] > value: if(status!=-1):
high = mid-1
print("Element found at %i location" %status)
elif numbersList[mid] <value:
low= mid+1 else:
else:
print("Element not found in the list")
return mid
return -1

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
#Recursive Binary Search Algorithm
def BinarySearchRecursive(numbersList, value, low= 0, high= -1):
if not numbersList: return -1
if(high == -1): high = len(numbersList)- 1
if low == high:
if numbersList[low] == value: return low
else: return - 1
mid=low + (high-low)//2
if numbersList[mid] >value: return BinarySearchRecursive(numbersList, value, low, mid-1)
elif numbersList[mid] < value: return BinarySearchRecursive(numbersList, value, mid+ 1,
high)
else: return mid
A=[534,246,933,127,277,321.454,565,220]
print(BinarySearchRecursive(A,277))
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Time Complexity

Case Time Complexity

Best Case O(1)


Average Case O(logn)
Worst Case O(logn)

Space Complexity

Space Complexity O(1)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
How many
Binary Search Analysis: Worst Case
comparisons?
?
Worst Case: divide until reach one item, or no match.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search Algorithm
Binary Search Analysis: Worst Case
• With each comparison we throw away ½ of the list

N ………… 1 comparison

N/2 ………… 1 comparison


Number of steps is at
most Log2N
N/4 ………… 1 comparison

N/8 ………… 1 comparison


.
.
.
1 ………… 1 comparison
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search Algorithm
Binary Search Analysis: Best Case Best Case:
1 comparison

Best Case: match from the firs comparison


1 7 9 12 33 42 59 76 81 84 91 92 93 99

Target: 59

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search Algorithm

Binary search reduces the work by half at each comparison

If array is not sorted  Linear Search


Best Case O(1)
Worst Case O(N)

If array is sorted  Binary search


Best Case O(1)
Worst Case O(Log2N)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting
Sorting: an operation that segregates items into groups according to specified
criterion.

A={3162134590}

A={0112334569}

 Sorting = ordering.
 Sorted = ordered based on a particular way.
 Generally, collections of data are presented in a sorted manner.

Examples of Sorting:
 Words in a dictionary are sorted (and case distinctions are ignored).
 Files in a directory are often listed in sorted order.
 The index of a book is sorted (and case distinctions are ignored).

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting
 Many banks provide statements that list checks in increasing order (by check
number).

 In a newspaper, the calendar of events in a schedule is generally sorted by date.

 Musical compact disks in a record store are generally sorted by recording artist.

Why Sorting required?


Imagine finding the phone number of your friend in your mobile phone, but the phone
book is not sorted.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting
 Most of the primary sorting algorithms run on different space and time
complexity.

 Time Complexity is defined to be the time the computer takes to run a program (or
algorithm in our case).

 Space complexity is defined to be the amount of memory the computer needs to


run a program.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting
 Types of Sorting Algorithms

There are many, many different types of sorting algorithms, but the primary ones are:

Bubble Sort

Selection Sort

Insertion Sort

Merge Sort

Quick Sort

Shell Sort

Radix Sort

Heap Sort

Bucket Sort

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting

Classification of Sorting Algorithms

Sorting algorithms arc generally categorized based on the following parameters.


• By Number of Comparisons
• By Number of Swaps
• By Memory Usage
• By Recursion
• By Adaptability

Another method of c classifying sorting algorithms is:


• Internal Sort
• External Sort

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting

Internal Sort
Sort algorithms that use main memory exclusively during the sort are called internal sorting algorithms.
This kind of algorithm assumes high-speed random access to all memory.

External Sort
Sorting algorithms that use external memory, such as tape or disk, during the sort come under this
category

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting

•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).

•External sorting typically uses a hybrid sort-merge strategy.

• In the sorting phase, chunks of data small enough to fit in main memory are read,
sorted, and written out to a temporary file.

• In the merge phase, the sorted sub-files are combined into a single larger file.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
This sorting technique is also known as exchange sort.

Arranges values by iterating over the list several times and in each iteration the larger
value gets bubble up to the end of the list.

This algorithm uses multiple passes and in each pass the first and second data items
are compared.

 If the first data item is bigger than the second, then the two items are swapped.
 Next the items in second and third position are compared and if the first one is larger
than the second, then they are swapped,
 otherwise no change in their order.
 This process continues for each successive pair of data items until all items are
sorted.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
Step-by-step example:
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest
number using bubble sort.

In each step, elements written in bold are being compared.


First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
(14258)
( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
(14258)(14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458)(12458)
(12458)(12458)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
Now, the array is already sorted, but our algorithm does not know if it is completed.

The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458)(12458)
(12458)(12458)
(12458)(12458)

(12458)(12458)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
Bubble Sort Algorithm:
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]
(B) Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 4: Exit

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort

Sort the given elements

1st Pass details

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort

def BubbleSort( A ):
for i in range( len( A) ):
for k in range( len( A) - 1, i, - 1 ):
if ( A[k] < A[k - 1 ] ):
swap(A,k,k-1)
def swap( A, x, y ):
temp= A[x]
A[x] = A[y]
A[y] = temp

A= [534,246,933, 127,277,321,454,565,220]
BubbleSort(A)
print( A)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
def bubbleSort(arr):
n = len(arr)
swapped = False
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]

if not swapped:
return # Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print("Sorted array is:" , arr)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Time & Space Complexity

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Space Complexity: O(1)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
Selection sort algorithm is one of the simplest sorting algorithm, which sorts the elements in an array by
finding the minimum element in each pass from unsorted part and keeps it in the beginning.

This sorting technique improves over bubble sort by making only one exchange in each pass.

This sorting technique maintains two sub arrays, one sub array which is already sorted and the other one
which is unsorted.

In each iteration the minimum element (ascending order) is picked from unsorted array and moved to sorted
sub array

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
Step-by-step example:
Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11

1st Pass: 11 25 12 22 64

2nd Pass: 11 12 25 22 64

3rd Pass: 11 12 22 25 64

4th Pass: 11 12 22 25 64

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
Selection Sort Algorithm:

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
Selection sort is an in-place sorting algorithm.
Selection sort works well for small files.
It is used for sorting the files with very large values and small keys.
This is because selection is made based on keys and swaps are made only when
required.

Advantages
• Easy to implement
• In-place sort (requires no additional storage space)

Algorithm
l. Find the minimum value in the list
2. Swap it with the value in the current position
3. Repeat this process for all the elements until the entire array is sorted
This algorithm is called selection sort since it repeatedly selects the smallest element.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
def SelectionSort( A ):
for i in range( len( A ) ):
least = i
for k in range( i + 1 , len( A)):
if A[k] < A[least]:
least = k
swap( A, least, i )

def swap( A, x, y ):
temp= A[x]
A[x] = A[y]
A[y] =temp

A= [54,26,93,17,77,31,44,55,20]
SelectionSort(A)
print(A)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Time & Space Complexity: Selection Sort

Worst Case Time Complexity [ Big-O ]: O(n2)


Best Case Time Complexity [Big-omega]: O(n2)
Average Time Complexity [Big-theta]: O(n2)
Space Complexity: O(1)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
• Merge sort is based on Divide and conquer method.

• It takes the list to be sorted and divide it in half to create two unsorted lists.

• The two unsorted lists are then sorted and merged to get a sorted list. The two
unsorted lists are sorted by continually calling the merge-sort algorithm;

• We eventually get a list of size 1 which is already sorted. The two lists of size 1
are then merged.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
Merge Sort Procedure:

This works as follows :

1. Divide the input which we have to sort into two parts in the middle. Call it the

left part and right part.

2. Sort each of them separately. Note that here sort does not mean to sort it using

some other method.

We use the same function recursively.

3. Then merge the two sorted parts.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
Step-by-step example:

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
Important Notes
Merging is the process of combining two sorted files to make one bigger sorted file.

Selection is the process of dividing a file into two parts: k smallest elements and a - k largest
elements.

• Selection and merging are opposite operations


 selection splits a list into two lists
 merging joins two files to make one file

• Merge sort accesses the data in a sequential manner

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
def MergeSort(A): while i<len(lefthalf):
if len(A)> 1: A[k]=lefthalf[i]
mid = len(A)//2 i=i+1
lefthalf = A[:mid] k=k+1
righthalf = A[mid:] while j<len(righthalf):
MergeSort(lefthalf)
MergeSort(righthalf) A[k]=righthalf[j]
i=j=k=0 j=j+1
while i<len(lefthalf) and k=k+1
j<len(righthalf):
if lefthalf[i]<righthalf[j]: A = [534,246,933,
A[k]=lefthalf[i] 127,277,321,454,565,220]
i=i+1 MergeSort(A)
else: print(A)
A[k]=righthalf[j]
j=j+1
k=k+ 1
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Quick Sort
Quick Sort Procedure:

1. Quicksort is a sorting algorithm based on the divide and conquer approach where

2. An array is divided into sub arrays by selecting a pivot element (element selected from the array).

While dividing the array, the pivot element should be positioned in such a way that elements less than

pivot are kept on the left side and elements greater than pivot are on the right side of the pivot.

3. The left and right sub arrays are also divided using the same approach. This process continues until each

subarray contains a single element.

4. At this point, elements are already sorted. Finally, elements are combined to form a sorted array.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Quick Sort
1. Select the Pivot Element
There are different variations of quicksort where the pivot element is selected from different
positions. Here, we will be selecting the rightmost element of the array as the pivot element.
2. Rearrange the Array
Now the elements of the array are rearranged so that elements that are smaller than the pivot are put on the left
and the elements greater than the pivot are put on the right.
3. The key process in quicksort is partition
Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted
array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x.
All this should be done in linear time.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Quick Sort
def partition(start, end, array):
pivot_index = start
pivot = array[pivot_index] def quick_sort(start, end, array):
while start < end: if (start < end):
while start < len(array) and array[start] <= pivot: p = partition(start, end, array)
start += 1 quick_sort(start, p - 1, array)
while array[end] > pivot:
quick_sort(p + 1, end, array)
end -= 1
if (start < end):
array[start], array[end] = array[end], array[start] array = [10, 17, 8, 9, 16, 5]
quick_sort(0, len(array) - 1, array)
array[end], array[pivot_index] = array[pivot_index], print(f'Sorted array: {array}')
array[end]
return end

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
www.mallareddyuniversity.ac.in

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
• Searching Algorithms are designed to check for
an element or retrieve an element from any
data structure where it is stored.
Searching • Based on the type of search operation, these
algorithms are generally classified into two
Techniques categories:
1. Sequential Search: In this, the list or
array is traversed sequentially and every
Data Structures using Python element is checked.
Dr. P. Praveen KumarFor example: Linear
Department Freshman Engineering
Linear Search Algorithm
Step 1: First, read the search element (Target element) in
the array.
Step 2: In the second step compare the search element with
the first element in the array.
Step 3: If both are matched, display “Target element is
found” and terminate the Linear Search function.
Step 4: If both are not matched, compare the search element
with the next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search
(Target) element is compared with the last element of the
array.
Step 6 – If the last element in the list does not match, the
Linear Search Function will be terminated, and the message
“Element

is not found” will be displayed.
Linear Search is defined as a sequential search algorithm that starts
at one end and goes through each element of a list until the
desired element is found, otherwise the search continues till the end
of the data set. It is the easiest searching algorithm.​
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Follow the given steps to solve the problem: • Given an array arr[] of N elements, the task is
• Set the first element of the array as the to write a function to search a given
current element. element x in arr[].
• If the current element is the target element, • Examples:
return its index. • Input: arr[] = {10, 20, 80, 30, 60, 50,110,
• If the current element is not the target 100, 130, 170}, x = 110;
element and if there are more elements in Output: 6
the array, set the current element to the next Explanation: Element x is present at index 6
element and repeat step 2.
• If the current element is not the target • Input: arr[] = {10, 20, 80, 30, 60, 50,110,
element and there are no more elements in 100, 130, 170}, x = 175;
the array, return -1 to indicate that the Output: -1
element was not found. Explanation: Element x is not present in arr[].

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search Implementation

def search(arr, N, x): # Driver Code


if __name__ == "__main__":
for i in range(0, N): arr = [2, 3, 4, 10, 40]
if (arr[i] == x): x = 10
return i N = len(arr)
return -1
# Function call
result = search(arr, N, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index",
result)
Time
complexity: O(N)
Data Structures using Python Dr. P. Praveen Kumar
Auxiliary
Department Freshman Engineering
Using “in” keyword in python:
The approach: we use a list instead of a vector or ArrayList, and
we can use the “in” keyword to check if an element is present in
the list.
v = [5, 15, 6, 9, 4] # create a list with initial values
key = 4 # variable to store the element to be searched
if key in v: # check if the element is present in the list
print(key, "is present in the list")
else:
print(key, "is not present in the list")

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Linear Search Recursive
Approach:
• Follow the given steps to solve the problem:
• If the size of the array is zero then, return -
1, representing that the element is not found.
This can also be treated as the base condition
of a recursion call.
• Otherwise, check if the element at the current
index in the array is equal to the key or not
i.e, arr[size – 1] == key
• If equal, then return the index of the found key.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
def linear_search(arr, key, size):
# If the array is empty we will return -1
if (size == 0):
return -1
elif (arr[size - 1] == key):
# Return the index of found key.
return size - 1
else:
return linear_search(arr, key, size - 1)

# Driver's code
if __name__ == "__main__":
arr = [5, 15, 6, 9, 4]
key = 4
size = len(arr)
ans = linear_search(arr, key, size) # Calling the Function
if ans != -1:
print("The element", key, "is found at",ans, "index of the given
array.")
else:
print("The element", key, "is not found.")
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Space Complexity
• Space complexity for linear search is O (n) as it does not use any extra
space where
n is the number of elements in an array.
• Time Complexity
Best- case complexity = O (1) occurs when the search element is present at
the first element in the search array.
Worst- case complexity = O (n) occurs when the search element is not present
in the
set of elements or array.
Average complexity = O (n) is referred to when the element is present
somewhere
in the search array

Time Complexity: O(N)


Auxiliary Space: O(N), for using recursive stack space.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Advantages of Linear Search:
• Linear search is simple to implement and easy to
understand.
• Linear search can be used irrespective of whether
the array is sorted or not. It can be used on
arrays of any data type.
• Does not require any additional memory.
• It is a well suited algorithm for small datasets.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Drawbacks of Linear Search:
• Linear search has a time complexity of O(n),
which in turn makes it slow for large datasets.
• Not suitable for large array.
• Linear search can be less efficient than other
algorithms, such as hash tables.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
When to use Linear Search:

• When we are dealing with a small dataset.


• When you need to find an exact value.
• When you are searching a dataset stored in
contiguous memory.
• When you want to implement a simple algorithm.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Summary:
• Linear search is a simple and flexible algorithm
for finding whether an element is present within
an array.
• It sequentially examines each element of the
array.
• The time complexity of linear search is O(n).
• It is used for searching databases, lists, and
arrays.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search

• Interval Search: These algorithms


are specifically designed for searching
in sorted data-structures.
• These type of searching algorithms
are much more efficient than Linear
Search as they repeatedly target the
center of the search structure and
divide the search space in half.
• For Example: Binary Search.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search
• Binary Search is a searching algorithm used in a
sorted array by repeatedly dividing the search
interval in half. The idea of binary search is to use
the information that the array is sorted and reduce
the time complexity to O(Log n).
• Step-by-step Binary Search Algorithm: We basically
ignore half of the elements just after one comparison.
• Compare x with the middle element.
• If x matches with the middle element, we return the
mid index.
• Else If x is greater than the mid element, then x can
only lie in the right half subarray after the mid
element. So we recur for the right half.
• Else (x is smaller) recur for the left half.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Binary Search Algorithm:
• The basic steps to perform Binary Search are
1. Sort the array in ascending order.
2. Set the low index to the first element of the array and
the high index to the last element.
3. Set the middle index to the average of the low and high
indices.
4. If the element at the middle index is the target
element, return the middle index.
5. If the target element is less than the element at the
middle index, set the high index to the middle index –
1.
6. If the target element is greater than the element at
the middle index, set the low index to the middle index
+ 1.
Data
7.Structures
Repeatusing Python 3-6 until Dr.
steps the P. Praveen Kumar is found Department
element or itFreshman
is Engineering
• Binary Search Algorithm can be
implemented in the following two ways
• Iterative Method
• Recursive Method

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Recursive Method (The recursive method
follows the divide and conquer approach)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
def binarySearch(arr, l, r, x):

# Check base case


if r >= l:

mid = l + (r - l) // 2

# If element is present at the middle


Python implementation: Recursive
itself
implementation of Binary Search if arr[mid] == x:
return mid

# If element is smaller than mid, then it


# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)

# Else the element can only be present


# in right subarray
else:
return binarySearch(arr, mid + 1, r,
x)

Data Structures using Python Dr. P. Praveen Kumar


else: Department Freshman Engineering
# Driver Code
arr = [2, 3, 4, 10, 40]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")

Time Complexity: O(log n)


Auxiliary Space: O(log n)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
def binarySearch(v, To_Find):
lo = 0
hi = len(v) - 1
Python
# for mid=lo-(hi-lo)/2
implementation while hi - lo > 1:
: Iterative mid = (hi + lo) // 2
Approach to if v[mid] < To_Find:
lo = mid + 1
Binary Search else:
hi = mid

if v[lo] == To_Find:
print("Found At Index", lo)
elif v[hi] == To_Find:
print("Found At Index", hi)
else:
print("Not Found")

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
if __name__ == '__main__':
v = [1, 3, 4, 5, 6]

To_Find = 1
binarySearch(v, To_Find)

To_Find = 6
binarySearch(v, To_Find)

To_Find = 10
binarySearch(v, To_Find)

Time Complexity: O (log


n)
Auxiliary Space: O (1)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Advantages of Binary Search:
• Binary search is faster than linear search, especially for large
arrays. As the size of the array increases, the time it takes to
perform a linear search increases linearly, while the time it takes
to perform a binary search increases logarithmically.
• Binary search is more efficient than other searching algorithms
that have a similar time complexity, such as interpolation search
or exponential search.
• Binary search is relatively simple to implement and easy to
understand, making it a good choice for many applications.
• Binary search can be used on both sorted arrays and sorted linked
lists, making it a flexible algorithm.
• Binary search is well-suited for searching large datasets that are
stored in external memory, such as on a hard drive or in the cloud.
• Binary search can be used as a building block for more complex
algorithms, such as those used in computer graphics and machine
learning.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Drawbacks of Binary Search:
• We require the array to be sorted. If the array is not sorted, we
must first sort it before performing the search. This adds an
additional O(n log n) time complexity for the sorting step, which
can make binary search less efficient for very small arrays.
• Binary search requires that the array being searched be stored in
contiguous memory locations. This can be a problem if the array
is too large to fit in memory, or if the array is stored on
external memory such as a hard drive or in the cloud.
• Binary search requires that the elements of the array be
comparable, meaning that they must be able to be ordered. This
can be a problem if the elements of the array are not naturally
ordered, or if the ordering is not well-defined.
• Binary search can be less efficient than other algorithms, such
as hash tables, for searching very large datasets that do not fit
in memory.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Applications of Binary search:
• Searching in machine learning: Binary search can be
used as a building block for more complex algorithms
used in machine learning, such as algorithms for
training neural networks or finding the optimal
hyperparameters for a model.
• Commonly used in Competitive Programming.
• Can be used for searching in computer graphics. Binary
search can be used as a building block for more complex
algorithms used in computer graphics, such as
algorithms for ray tracing or texture mapping.
• Can be used for searching a database. Binary search can
be used to efficiently search a database of records,
such as a customer database or a product catalog.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
When to use Binary Search:
• When searching a large dataset as it has a time
complexity of O(log n), which means that it is
much faster than linear search.
• When the dataset is sorted.
• When data is stored in contiguous memory.
• Data does not have a complex structure or
relationships.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Summary:
• Binary search is an efficient algorithm for
finding an element within a sorted array.
• The time complexity of the binary search is
O(log n).
• One of the main drawbacks of binary search is
that the array must be sorted.
• Useful algorithm for building more complex
algorithms in computer graphics and machine
learning.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Sorting Techniques

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
• Bubble sort is a sorting algorithm that compares two
adjacent elements and swaps them until they are in the
intended order.
• Just like the movement of air bubbles in the water that
rise up to the surface, each element of the array move
to the end in each iteration. Therefore, it is called a
bubble sort.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Working of Bubble Sort
Suppose we are trying to sort the
elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index,
compare the first and the second
elements.
2. If the first element is greater
than the second element, they
are swapped.
3. Now, compare the second and the
third elements. Swap them if
they are not in order.
4. The above process goes on until
the last element.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
2. Remaining
Iteration
• The same process goes on for the remaining
iterations.
• After each iteration, the largest element among the
unsorted elements is placed at the end.
• In each iteration, the comparison takes
place up to the last unsorted element.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
The array is sorted when all the unsorted elements are
placed at their correct positions.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
Algorithm
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1

if leftElement > rightElement


swap leftElement and rightElement
end bubbleSort

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort Code in Python
def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

data = [-2, 45, 0, 11, -9]


Sorted_1 = bubbleSort(data)
print('Sorted Array in Ascending Order:', Sorted_1)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Optimized Bubble Sort Algorithm
• In the above algorithm, all the comparisons are made even
if the array is already sorted.
• This increases the execution time.
• To solve this, we can introduce an extra variable swapped.
The value of swapped is set true if there occurs swapping
of elements. Otherwise, it is set false.
• After an iteration, if there is no swapping, the value
of swapped will be false. This means elements are already
sorted and there is no need to perform further iterations.
• This will reduce the execution time and helps to optimize
the bubble sort.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Optimized Bubble Sort in Python
def bubbleSort(array):
for i in range(len(array)):
# keep track of swapping
data = [-2, 45, 0, 11, -9]
swapped = False
Sorted_1 = bubbleSort(data)
for j in range(0, len(array) - i - 1): print('Sorted Array in
if array[j] > array[j + 1]: Ascending Order:', Sorted_1)

temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
swapped = True
# no swapping means the array is already sorted
if not swapped:
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort
Complexity
Time Complexity

Best O(n)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability Yes

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Complexity in Detail
Bubble Sort compares the adjacent elements.

Cycle Number of Comparisons

1st (n-1)

2nd (n-2)

3rd (n-3)

....... ......

last 1

Hence, the number of comparisons is


(n-1) + (n-2) + (n-3) +.....+ 1 = n(n-1)/2, nearly equals to n2
Hence, Complexity: O(n2)
Also, if we observe the code, bubble sort requires two loops. Hence, the
complexity is n*n = n2

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
1. Time Complexities

• Worst Case Complexity: O(n2)


If we want to sort in ascending order and the array is in
descending order then the worst case occurs.
• Best Case Complexity: O(n)
If the array is already sorted, then there is no need for sorting.
• Average Case Complexity: O(n2)
It occurs when the elements of the array are in jumbled order
(neither ascending nor descending).

2. Space Complexity

• Space complexity is O(1) because an extra variable is used for


swapping.
• In the optimized bubble sort algorithm, two extra variables are
used. Hence, the space complexity will be O(2).

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Bubble Sort Applications

Bubble sort is used if


• complexity does not matter
• short and simple code is preferred

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort
Algorithm

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
• Selection sort is a sorting algorithm that selects the
smallest element from an unsorted list in each iteration
and places that element at the beginning of the unsorted
list.
Working of Selection Sort

1.Set the first element as minimum.

Select first element as


minimum​

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
2. 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.

Compare minimum Dr.


Data Structures using Python with the Kumar
P. Praveen remaining Department Freshman Engineering
3. After each iteration, minimum is placed in the
front of the unsorted list.

Swap the first with


minimum​

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
• For each iteration, indexing starts from the first
unsorted element. Step 1 to 3 are repeated until all the
elements are placed at their correct positions.

The first
Data Structures iteration
using Python The second iteration
Dr. P. Praveen Kumar Department Freshman Engineering
The fourth iteration

The third iteration

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort Algorithm
selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the
minimum for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort Code in Python
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
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)
Se_sorted = selectionSort(data, size)
print('Sorted Array in Ascending Order:',
Se_sorted)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort Complexity
Time Complexity

Best O(n2)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability No

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Selection Sort Applications

The selection sort is used when


• a small list is to be sorted
• cost of swapping does not matter
• checking of all the elements is compulsory
• cost of writing to a memory matters like in flash
memory (number of writes/swaps is O(n) as compared
to O(n2) of bubble sort)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Insertion Sort Algorithm

• Insertion sort is a sorting algorithm that places an


unsorted element at its suitable place in each
iteration.
• Insertion sort works similarly as we sort cards in our
hand in a card game.
• We assume that the first card is already sorted then, we
select an unsorted card. If the unsorted card is greater
than the card in hand, it is placed on the right
otherwise, to the left. In the same way, other unsorted
cards are taken and put in their right place.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Working of Insertion
Sort
Suppose we need to sort the following array.

Initial array

1. The first element in the array


is assumed to be sorted. Take
the second element and store
it separately in key.

Compare key with the first


element. If the first element
is greater than key,
If the first element is greater
then key is placed in front of than key, then key is placed in
Datathe first
Structures using element.
Python Dr. P. Praveen Kumar
front of the first element.
Department Freshman Engineering
2. Now, the first two
elements are sorted.

Take the third element


and compare it the elements
on the left of it. Placed it
just behind the
element smaller than it. If
there is no element smaller
than it, then place it at
the beginning of the array.

Place 1 at the
beginning
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
3. Similarly, place
every unsorted element
at its correct
position.

Place 4 behind 1 Place 3 behind 1 and the array is


Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
sorted
Insertion Sort in Python
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = key

data = [9, 5, 1, 4, 3]
In_sorted = insertionSort(data)
Data Structures using Python
print('Sorted Dr. P. Praveen Kumar
Array in Ascending Order:', In_sorted)
Department Freshman Engineering
Insertion Sort Complexity
Time Complexity

Best O(n)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability Yes

Insertion Sort Applications

The insertion sort is used when:


• the array is has a small number of elements
• there are only a few elements left to be sorted
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
•Merge Sort Algorithm

• Merge Sort is based on


the principle of Divide
and Conquer Algorithm.
• Here, a problem is
divided into multiple
sub-problems. Each sub-
problem is solved
individually. Finally,
sub-problems are combined
to form the final
Data Structures using Python
solution. Dr. P. Praveen Kumar Department Freshman Engineering
Divide and Conquer Strategy Divide
• If q is the half-way point between
• Using the Divide and p and r, then we can split the
subarray A[p..r] into two
Conquer technique, we divide arrays A[p..q] and A[q+1, r].
a problem into subproblems.
When the solution to each Conquer
• In the conquer step, we try to sort
subproblem is ready, we both the
'combine' the results from subarrays A[p..q] and A[q+1, r]. If
the subproblems to solve the we haven't yet reached the base
case, we again divide both these
main problem. subarrays and try to sort them.

• Suppose we had to sort an Combine


• When the conquer step reaches the
array A. A subproblem would base step and we get two sorted
be to sort a sub-section of subarrays A[p..q] and A[q+1, r] for
this array starting at array A[p..r], we combine the
results by creating a sorted
index p and ending at array A[p..r] from two sorted
index
Data r,using
Structures denoted
Python as A[p..r]. subarrays A[p..q]
Dr. P. Praveen Kumar and Freshman
Department A[q+1,Engineering
r].
MergeSort Algorithm

• The MergeSort function repeatedly divides the array into


two halves until we reach a stage where we try to perform
MergeSort on a subarray of size 1 i.e. p == r.
• After that, the merge function comes into play and
combines the sorted arrays into larger arrays until the
whole array is merged.
MergeSort(A, p, r):
if p > r
return
q = (p+r)/2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
• To sort an entire array,
we need to call
MergeSort(A, 0, length(A)-
1).

• As shown in the image


below, the merge sort
algorithm recursively
divides the array into
halves until we reach the
base case of array with 1
element. After that, the
merge function picks up
the sorted sub-arrays and
merges them to gradually
sort the entire array.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
The merge Step of Merge
Sort
• Every recursive algorithm is dependent on a base case
and the ability to combine the results from base cases.
Merge sort is no different. The most important part of
the merge sort algorithm is, you guessed it, merge step.
• The merge step is the solution to the simple problem of
merging two sorted lists(arrays) to build one large
sorted list(array).
• The algorithm maintains three pointers, one for each of
the two arrays and one for maintaining the current index
of the final sorted array.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Writing the Code for Merge
Algorithm
Our task is to merge two subarrays A[p..q] and A[q+1..r] to create
a sorted array A[p..r]. So the inputs to the function are A, p, q
and r

The merge function works as follows:


1.Create copies of the subarrays L <- A[p..q] and M
<- A[q+1..r].
2.Create three pointers i, j and k
1.i maintains current index of L, starting at 1
2.j maintains current index of M, starting at 1
3.k maintains the current index of A[p..q], starting at p.
3.Until we reach the end of either L or M, pick the larger
among the elements from L and M and place them in the correct
position at A[p..q]
4.When we run out of elements in either L or M, pick up the
remaining elements and put in A[p..q]
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
while i < len(L):
Merge Sort Code in Python array[k] = L[i]
def mergeSort(array): i += 1
k += 1
if len(array) > 1:
r = len(array)//2 while j < len(M):
array[k] = M[j]
L = array[:r] j += 1
M = array[r:] k += 1

mergeSort(L)
mergeSort(M) # Print the array
def printList(array):
i = j = k = 0 for i in range(len(array)):
while i < len(L) and j < print(array[i], end=" ")
len(M): print()

if L[i] < M[j]: # Driver program


array[k] = L[i] if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
i += 1 mergeSort(array)
else: print("Sorted array is: ", array)
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Merge Sort
Complexity
Time Complexity

Best O(n*log n)

Worst O(n*log n)

Average O(n*log n)

Space Complexity O(n)

Stability Yes

Merge Sort Applications


•Inversion count problem
•External sorting
•E-commerce applications

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Quicksort Algorithm

Quicksort is a sorting algorithm based on the divide and


conquer approach where
1.An array is divided into subarrays by selecting a pivot
element (element selected from the array).

While dividing the array, the pivot element should be


positioned in such a way that elements less than pivot are
kept on the left side and elements greater than pivot are
on the right side of the pivot.
2.The left and right subarrays are also divided using the
same approach. This process continues until each subarray
contains a single element.
3.At this point, elements are already sorted. Finally,
elements are combined to form a sorted array.
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Working of Quicksort Algorithm

1. Select the Pivot Element


There are different variations of quicksort where the
pivot element is selected from different positions. Here,
we will be selecting the rightmost element of the array
as the pivot element.

Select a pivot element

2. Rearrange the Array


Now the elements of the array are rearranged so that elements
that are smaller than the pivot are put on the left and the
elements greater than the pivot are put on the right.

Put all the smaller elements on the left and greater on the right of
Data Structures
pivot using Python
element Dr. P. Praveen Kumar Department Freshman Engineering
Here's how we rearrange the array:
a.A pointer is fixed at the pivot element. The pivot element
is compared with the elements beginning from the first
index.

Comparison of pivot element with element beginning from the first


index

b.If the element is greater than the pivot element, a second


pointer is set for that element.

If the element is greater than the pivot element, a second pointer is set
for that element.​
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
• Now, pivot is compared with • Again, the process is
other elements. If an repeated to set the next
element smaller than the greater element as the
pivot element is reached, second pointer. And, swap
the smaller element is it with another smaller
swapped with the greater element.
element found earlier.

The process is repeated to set the next


greater element as the second pointer.

Pivot is compared with other


Data Structures
elements.​using Python Dr. P. Praveen Kumar Department Freshman Engineering
• The process goes on until the second last element is
reached.

• Finally, the pivot element is swapped with the second


pointer.

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
3. Divide Subarrays
• Pivot elements are again chosen for the left and the
right sub-parts separately. And, step 2 is repeated.

The subarrays
are divided
until each
subarray is
formed of a
single element.
At this point,
the array is
already sorted.

Select pivot element of in each half and put at correct place using recursion
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Visual Illustration of Quicksort Algorithm

Sorting the elements on the left of pivot using recursion

Data Structures using Python Dr.Sorting the elements


P. Praveen Kumar on the right of pivot using Freshman
Department recursionEngineering
Quicksort Code in Python
def partition(array, low, high):
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1
Data Structures using Python
# swapping element at i Dr.
withP. Praveen Kumarat j
element Department Freshman Engineering
# swap the pivot element with the greater element
specified by i​
(array[i + 1], array[high]) = (array[high], array[i + 1])​

# return the position from where partition is done​
return i + 1
# function to perform quicksort​
def quickSort(array, low, high):​
if low < high:​

# find pivot element such that​
# element smaller than pivot are on the left​
# element greater than pivot are on the right​
pi = partition(array, low, high)​

# recursive call on the left of pivot​
quickSort(array, low, pi - 1)​

# recursive call on the right of pivot​
quickSort(array, pi + 1, high)
Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering
Quicksort
Complexity
Time Complexity

Best O(n*log n)

Worst O(n2)

Average O(n*log n)

Space Complexity O(log n)

Stability No

Quicksort Applications
Quicksort algorithm is used when
• the programming language is good for recursion
• time complexity matters
• space complexity matters

Data Structures using Python Dr. P. Praveen Kumar Department Freshman Engineering

You might also like