0% found this document useful (0 votes)
22 views79 pages

DSA Secion A

The document provides an overview of data structures and algorithms, detailing the importance of selecting appropriate data structures based on project requirements. It explains the differences between linear and non-linear data structures, introduces algorithms, and outlines the qualities of a good algorithm along with the process of algorithm development and analysis. Additionally, it covers time complexity, memory allocation for arrays, and methods for accessing array elements.

Uploaded by

manunalluri76
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)
22 views79 pages

DSA Secion A

The document provides an overview of data structures and algorithms, detailing the importance of selecting appropriate data structures based on project requirements. It explains the differences between linear and non-linear data structures, introduces algorithms, and outlines the qualities of a good algorithm along with the process of algorithm development and analysis. Additionally, it covers time complexity, memory allocation for arrays, and methods for accessing array elements.

Uploaded by

manunalluri76
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/ 79

Data Structures &

Algorithms
DSA Team
Jan-June 2025
Data Structures
•A data structure is a storage that is used to store Another Example:
and organize data. If we want to store data about people we are related to, we
use a family tree as the data structure. We choose a family
•It is a way of arranging data on a computer so that tree as the data structure because we have information
it can be accessed and updated efficiently. about people we are related to and how they are related,
and we want an overview so that we can easily find a
•Depending on your requirement and project, it is specific family member, several generations back.
important to choose the right data structure for
your project.

•For example, if you want to store data sequentially in


the memory, then you can go for the Array data
structure.
Choice of right Data Structure

Understand the Problem Requirements


• Relationships: Is data need sequential or hierarchical or graph-like relationship?
• Nature of Operations: What kind of operations are needed? (e.g., search, insertion, deletion, traversal, sorting).
• Frequency of Operations: How often are these operations performed?
• Size of Data: Is the dataset small, large, or expected to grow significantly?
• Performance Constraints: Is there a need for high speed, low memory usage, or both?
• Static vs. Dynamic: Does the data size change frequently? Use dynamic structures like linked lists if yes; arrays if
no.
Types of Data Structures
Now Abstract Data Structures further divided into Linear and
Non-Linear Data Structures
• In Computer Science there are two different
Linear Data Structure: A linear data structure is one in which
kinds of data structures.
the data is stored in a sequential order and are linked to the
• Primitive Data Structures are basic data elements before and after them.
structures provided by programming Non-Linear Data Structure: Elements in non-linear data
languages to represent single values, such as structures are not in any sequence.
integers, floating-point numbers,
characters, and Booleans.
• Non-Primitive (Abstract) Data
Structures are higher-level data structures
that are built using primitive data types and
provide more complex and specialized
operations. Some common examples of
abstract data structures include arrays,
linked lists, stacks, queues, trees, and
graphs.
Linear Vs Non-Linear Data Structure
Linear Data Structure Non-Linear Data Structure
Overview The elements are joined to one another and The elements are grouped hierarchically or non-
arranged sequentially or linearly in this structure. linearly in this structure.
Types A linear data structure includes arrays, linked lists, A non-linear data structure is made up of trees and
queues, and stacks. graphs.
Implementation They are simple to execute because to the linear They are challenging to put in place because of the
organization. non-linear structure.
Traversal Because a linear data structure has only one A non-linear data structure’s data element cannot
level, traversing each data item requires only one be retrieved in a single run. It needs traversing many
run. runs.
Arrangement Each data item is linked to the one before it and Each item is linked to several others.
the one after it.
Memory The memory usage is inefficient in this case. Memory is used to its full potential in this way.
Utilization
Levels There is no hierarchy in this data structure, and The data items are placed in various levels in this
all data items are grouped on a single level. method.
Time Complexity With increasing input size, the time complexity of With increasing input size, the time complexity
linear data structures increases. of non-linear data structures frequently stays the
same.
Applications Linear data structures are mostly utilized in Image processing and Artificial Intelligence both use
software development. non-linear data structures.
Introduction to Algorithms
Qualities of a Good Algorithm
•An algorithm is a set of commands that must be
followed for a computer to perform calculations • Efficiency: A good algorithm should perform its task quickly and
or other problem-solving operations. According, use minimal resources.
to its formal definition, an algorithm is a finite set • Correctness: It must produce the correct and accurate output for
of instructions carried out in a specific order to all valid inputs.
perform a particular task. • Clarity: The algorithm should be easy to understand and
comprehend, making it maintainable and modifiable.
• Scalability: It should handle larger data sets and problem sizes
•The word Algorithm means” A set of finite rules without a significant decrease in performance.
or instructions to be followed in calculations or • Reliability: The algorithm should consistently deliver correct
other problem-solving operations” results under different conditions and environments.
• Optimality: Striving for the most efficient solution within the
•“A procedure for solving a mathematical given problem constraints.
problem in a finite number of steps that • Robustness: Capable of handling unexpected inputs or errors
gracefully without crashing.
frequently involves recursive operations.”
• Adaptability: Ideally, it can be applied to a range of related
problems with minimal adjustments.
• Simplicity: Keeping the algorithm as simple as possible while
meeting its requirements, avoiding unnecessary complexity.
Algorithms
Properties of Algorithm

 It should terminate after a finite time.

 Problem: A problem can be defined as a real-world problem  It should produce at least one output.
or real-world instance problem for which you need to
develop a program or set of instructions. An algorithm is a  It should take zero or more input.
set of instructions.
  It should be deterministic means giving the
Algorithm: An algorithm is defined as a step-by-step
process that will be designed for a problem. same output for the same input case.
 Input: After designing an algorithm, the algorithm is given  Every step in the algorithm must be effective
the necessary and desired inputs.
i.e. every step should do some work.
 Processing Unit: The input will be passed to the processing
unit, producing the desired output.
 Output: The outcome or result of the program is referred to
as the output.
How to Develop an Algorithm
1. Understand the problem.

2. Identify the output of the problem.

3. Identify inputs required by the problem and choose the associated data structure.

4. Design a logic that will produce the desired output from the given inputs.

5. Test the algorithm for different sets of input data.

6. Repeat steps 1 to 5 till the algorithm produces the desired results for all types of input and
rules.
Stepwise Refinement: Top-Down

Break a complex problem into smaller problems
 Write a stub for each smaller problem

Fill in algorithm for each sub-step.
 Possibly using stepwise refinement for the sub-step


Advantages
 Bugs are easier to find

adding less code in each refinement
 Functions might be reusable
Algorithm Analysis
• The analysis of algorithms is the process of evaluating the performance and
efficiency of an algorithm.
• It involves determining the computational resources (like time and space) that
an algorithm requires for execution.
• This evaluation helps to compare algorithms and choose the most appropriate
one for a specific problem.

• The analysis is a process of estimating the efficiency of an algorithm. There are


two fundamental parameters based on which we can analysis the algorithm:
• Space Complexity: The space complexity can be understood as the amount of space required by an
algorithm to run to completion.
• Time Complexity: Time complexity is a function of input size n that refers to the amount of time needed
by an algorithm to run to completion.
Time Complexity
• The time complexity of an algorithm quantifies the amount of time taken
by an algorithm to run as a function of the length of the input. Note that the
time to run is a function of the length of the input and not the actual
execution time of the machine on which the algorithm is running on.
• The valid algorithm takes a finite amount of time for execution. The time
required by the algorithm to solve given problem is called time
complexity of the algorithm. Time complexity is very useful measure in
algorithm analysis.
• It is the time needed for the completion of an algorithm. To estimate the
time complexity, we need to consider the cost of each fundamental
instruction and the number of times the instruction is executed.
Some Rules to determine complexity due to types of statements

RULE #1: Simple program statements are assumed to take a constant amount
of time which is O(1)
RULE #2: Differences in execution time of simple statements is ignored.
RULE #3: In conditional statements, the worst case is always used.
RULE #4:The running time of a sequence of steps has the order of the
running time of the largest (the sum rule).

RULE #5:If two processes are constructed such that second process is repeated a
number of times for each n in the first process, then O is equal to the
product of the orders of magnitude for both products (the product rule)
RULE #1: RULE #2:

Each statement takes constant time O(1),


regardless of the specifics of the operation.
RULE #3: RULE #4:
RULE #5:
• Assignment : O(1)
• Procedure Entry : O(1)
• Procedure Exit : O(1)
• if A then B else C :
– time for test A + O(max{B,C})
• loop :
– sum over all iterations of the time for each iteration.
• Combine using Sum and Product rules.
• Exception: Recursive Algorithms
Some Examples to understand more
Some Examples to understand more
Some Examples to understand more
Time Complexity
Worst-case time complexity: For 'n' input size, the worst-
case time complexity can be defined as the maximum
amount of time needed by an algorithm to complete its Searching for an element
execution. int arr[] = {5, 2, 3, 7, 1};
Thus, it is nothing but a function defined by the maximum int x = 3; // Target element
number of steps performed on an instance having an input
size of n.
Average case time complexity: For 'n' input size, the
average-case time complexity can be defined as the
average amount of time needed by an algorithm to
complete its execution.
Thus, it is nothing but a function defined by the average
number of steps performed on an instance having an input
size of n.
Best case time complexity: For 'n' input size, the best-
case time complexity can be defined as the minimum
amount of time needed by an algorithm to complete its
execution.
Thus, it is nothing but a function defined by the minimum
number of steps performed on an instance having an input
Basic Asymptotic Efficiency Classes
Comparison of Complexity Classes
Array
• An array in data structures is a collection of
elements, all of the same data type, stored in
contiguous memory locations. It is one of the
simplest and most widely used data structures due to
its efficiency and ease of use.
• Key Features of Arrays
1. Fixed Size: Arrays have a predefined size, which
cannot be changed after allocation.
2. Homogeneous Data: All elements in the array are of
the same data type (e.g., integers, floats, characters).
3. Indexed Access: Each element can be accessed
directly using its index.
4. Contiguous Memory: All elements are stored in
adjacent memory locations.
Notation  A[K]
Length of Array = UB-LB+1
#include <stdio.h>
int main()
{
int Arr[9]={9,8,-
1,1,4,2,6,15,3};
int i; Arr[] = {9,8,1,-1,4,2,6,15,3}
for(i=0;i<=4;i++)
printf("%d",Arr[i]); Arr[0] = 9 Arr[1] = 8
Arr[2] = 1 Arr[3] = -1
Arr[4] = 4 Arr[5] = 2
return 0; Arr[6] = 6 Arr[7] = 15
} Arr[8] = 3
Types of Arrays
One Dimensional Array:
((An Array whose elements
are specified by a single
subscript Ex. A[0] ))

Multi Dimensional Array:


(An Array whose elements
are specified by two or
more than two subscripts.
Ex. A[10][10] is a two-
dimensional array )
Basic Operation of Array
Memory allocation of 1-D array
•As stated above, all the data elements of an array are
stored at contiguous locations in the main memory. The
name of the array represents the base address or the
address of the first element in the main memory. Each
element of the array is represented by proper indexing.
We can define the indexing of an array in the below ways
- In the above image, we have shown the
• 0 (zero-based indexing): The first element of the array memory allocation of an array arr of size 5.
will be arr[0].
• 1 (one-based indexing): The first element of the array The array follows a 0-based indexing
will be arr[1]. approach.
• n (n - based indexing): The first element of the array
can reside at any random index number. The base address of the array is 100 bytes. It is
the address of arr[0].

Here, the size of the data type used is 4 bytes;


therefore, each element will take 4 bytes in the
memory.
How to access an element from the array?
• We required the information given below to
access any random element from the array -
o Base Address of the array.
o Size of an element in bytes. Example
Suppose an array, A [-10 ..... +2 ] having Base
o Type of indexing, array follows.
address (BA) = 999 and size of an element = 2
•The formula to calculate the address to access an bytes, find the location of A[-1].
array element –
BA = 999, Size of an element = 2 bytes
•Representation of Linear Array in memory  LB = -10, UB = 2

•LOC(LA[k]) = BASE(LA) + w (k- LB) LOC(LA[k]) = BASE(LA) + w (k- LB)

•W # of words per memory cell. Loc(A[-1]) = 999 + 2 x [(-1) - (-10)]


= 999 + 18
= 1017
Example
•Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the size of each element is 2
bytes in the memory, find the address of A[1700].
•Solution:
•Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
•Formula used:
Address of A[I] = B + W * (I – LB)
•Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Memory allocation of 2-D array 2-D array
To find the address of any element in a 2-
The 2-dimensional array can be defined as an array of arrays. Dimensional array there are the following two
The 2-Dimensional arrays are organized as matrices which can ways-
be represented as the collection of rows and columns as
array[M][N] where M is the number of rows and N is the • Row Major Order
number of columns.
• Column Major Order
Row Major Order Column Major Order

Address of A[I][J] = B + W * ((I – LR) * N + (J – LC)) Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))

I = Row Subset of an element whose address to be found,


I = Row Subset of an element whose address to be found, J = Column Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found, B = Base address,
B = Base address, W = Storage size of one element store in any array(in byte),
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given
LR = Lower Limit of row/start row index of the matrix(If not
given assume it as zero), assume it as zero),
LC = Lower Limit of column/start column index of the LC = Lower Limit of column/start column index of matrix(If not
matrix(If not given assume it as zero), given assume it as zero),
N = Number of column given in the matrix. M = Number of rows given in the matrix.
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory. Find the
address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210

500 + 2 * ((8 – 1) * 15 + (6 – 1))


= 500 + 2 * ((7) * 15 + (5))
= 500 + 2 * (110)
500+220=720
Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of each element is 1
Byte in memory find the address of arr[8][6] with the help of column-major order.
Solution:
Given:

Base address B = 100


Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used

Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))


Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
Traversing as Array

•TRAVERSE (LA, LB, UB)

Here LA is a linear array with lower bound


LB and upper bound UB
1.[Initialize Counter] Set K=LB
2.Repeat steps 3 and 4 while K<=UB
3.Apply PROCESS LA[K].
4.[Increase Counter] Set K=K+1.

End of step 2
5.Exit
Insertion in Array

INSERT (LA, N, K, ITEM)


Here LA is a linear array with N elements,
K is position at which we have to put
ITEM. ITEM is the element to be inserted.


1. [Initialize Counter] Set J=N.
2. Repeat steps 3 and 4 while J>=K.
3. Set LA[J+1] = LA[J].
4. [Decrease Counter] Set J=j-1.
5. [Inserting ITEM] Set LA[K]=ITEM.
6. [Reset Number of Elements]. Set
N=N+1.
7. Exit
Deletion from Array
Searching in an Array
• Searching is the fundamental process of locating a
specific element or item within a collection of data.
• The primary objective of searching is to determine
whether the desired element exists within the data, and if
so, to identify its precise location or retrieve it.

• Linear Search
• Binary Search
Linear Search

In Linear Search, we Algorith LinearSearch (data, arr[], N)


iterate over all the
elements of the array and
check if it the current 1. Set i = 0
element is equal to the 2. while ( i < n or arr[i] != data )
target element. If we find
any element to be equal 2.1 i++
to the target element, 3. If i = n
then return the index of 3.1 Display “Data Not Found”
the current element. else
Otherwise, if no element is 3.1 Display “Data is found at
equal to the target position i”
element, then return -1 as
the element is not found.
Linear search is also
known as sequential
search.
Linear Search Complexity

Arr[5] = {1,2,3,4,5}

Best Case = O(1)

Worst Case = O(N)

Average Case = O(N)


Binary Search
0 1 2 3 4 5 6
• Binary Search is a searching
algorithm for finding an element's 12 15 16 56 63 88 92
position in a sorted array.
• Here, the element is always searched
in the middle of a portion of an array. Let us suppose we are looking for 15
Beg = 0
• Binary search follows the divide and End = 6
conquer approach in which the list is Mid = int(Beg+End)/2 (0+6)/2 = 3
divided into two halves, and the item Arr[3] = 56 < 15(data item we were looking for)
is compared with the middle element
of the list. End = Mid-1; End = 3-1 = 2
• If the match is found then, the Now search in 0 1 2
location of the middle element is 12 15 16
returned. Otherwise, we search into
either of the halves depending upon Mid = (0+2)/2 = 1
the result produced through the Arr[1] = 15 = 15 (data item we were looking for)
match.
Binary Search
Complexity of Binary Search

• Best Case = O(1)

• Worst Case = O(logN)

• Average Case = O(logN)


Sorting
• Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical order.

In-place Sorting
Sorting algorithms may require some extra space for
comparison and temporary storage of few data
elements.
These algorithms do not require any extra space and
sorting is said to happen in-place, or for example,
within the array itself.
Example: Bubble Sort, Insertion Sort, Selection Sort

Out-place Sorting
In some sorting algorithms, the program requires
space which is more than or equal to the elements
being sorted. Sorting which uses equal or more space
is called Out-place sorting.
Example: Merge-sort, Radix Sort, Counting Sort,
Bucket Sort.
Stable Sorting Internal Sorting
• When two same data appear in •When all data is placed in the main
the same order in sorted data without memory or internal memory then sorting is called internal
changing their position is called stable sort. sorting. Here the problem cannot take input beyond its size.

• Example: merge sort, insertion sort, Example: heap sort, bubble sort, selection sort, quick sort,
bubble sort. shell sort, insertion sort.

Unstable Sorting External Sorting :


• When two same data appear in •When all data that needs to be sorted cannot be placed in
the different order in sorted data it is called memory at a time, the sorting is called external sorting.
unstable sort. External Sorting is used for the massive amount of data. Some
external storage like hard disks and CDs are used for external
• Example: quick sort, heap sort, shell sort. sorting.

Example: Merge sort, Tag sort, Polyphase sort, Four tape sort,
External radix sort, Internal merge sort, etc.
Insertion Sorting
Selection Sort
• Selection Sort is a comparison-
based sorting algorithm. It sorts an
array by repeatedly selecting
the smallest (or largest) element
from the unsorted portion and
swapping it with the first unsorted
element. This process continues until
the entire array is sorted.

1. First, we find the smallest element


and swap it with the first element.
This way we get the smallest
element at its correct position.

2. Then we find the smallest among


remaining elements (or second
smallest) and swap it with the
second element.

3. We keep doing this until we get all


elements moved to correct position.
Selection Sorting
Efficiency of Selection Sort
In selection sort, there are n – 1 comparisons during Pass 1 to find the
smallest element, n – 2 comparisons during Pass 2 to find the second
smallest element, and so on.
Total number of comparisons = (n – 1) + (n – 2) + (n – 3) + … + 3 + 2 + 1
= n(n – 1)/2
n(n – 1)/2 is of O(n2) order. Therefore, the selection sort algorithm is of
the order O(n2).
Bubble Sort
• Bubble Sort is the simplest
sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in
the wrong order.

• We sort the array using multiple passes. After


the first pass, the maximum element goes to
end (its correct position). Same way, after
second pass, the second largest element goes
to second last position and so on.

• In every pass, we process only those elements


that have already not moved to correct
position. After k passes, the largest k elements
must have been moved to the last k positions.

• In a pass, we consider remaining elements and


compare all adjacent and swap if larger
element is before a smaller element. If we
keep doing this, we get the largest (among the
remaining elements) at its correct position.
Bubble Sort
Algorithm BubbleSort ( A [],n )
{

1. for ( pass = 1 to n-1 )


1.1 for ( j= 0 to n – 1 – pass )
1.1.1 If ( A [j] > A [j+1] )
1.1.1.1 t = A [j]
1.1.1.2 A [j] = A [j+1]
1.1.1.3 A [j+1] = t
}
Determining the Efficiency of Bubble Sort Algorithm
The efficiency of a sorting algorithm is measured in terms of number of
comparisons.
In bubble sort, there are n – 1 comparisons in Pass 1, n – 2 comparisons in
Pass 2, and so on.
Total number of comparisons = (n – 1) + (n – 2) + (n – 3) + … + 3 + 2 + 1
= n(n – 1)/2.
n(n – 1)/2 is of O(n2) order. Therefore, the bubble sort algorithm is of the
order O(n2).
Merge Sort
Merge-Sort: Merge Example

A:
3 5 15 28 30 6 10 14

L: R:
3
2 15
3 28
7 30
8 6
1 10
4 14
5 22
6

i=0 j=0
Merge-Sort: Merge Example

A:
3
1 5 15 28 30 6 10 14

k=0

L: R:
3
2 15
3 28
7 30
8 6
1 10
4 14
5 22
6

i=0 j=0
Merge-Sort: Merge Example

A:
1 25 15 28 30 6 10 14

k=1

L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6

i=0 j=1
Merge-Sort: Merge Example

A:
1 2 3 28 30
15 6 10 14

k=2

L: R:
2 3 7 8 6
1 10
4 14
5 22
6

i=1 j=1
Merge-Sort: Merge Example

A:
1 2 3 4 6 10 14

k=3

L: R:
2 3 7 8 6
1 10
4 14
5 22
6

i=2 j=1
Merge-Sort: Merge Example

A:
1 2 3 4 5 6 10 14

k=4

L: R:
2 3 7 8 6
1 10
4 14
5 22
6

i=2 j=2
Merge-Sort: Merge Example

A:
1 2 3 4 5 6 10 14

k=5

L: R:
2 3 7 8 6
1 10
4 14
5 22
6

i=2 j=3
Merge-Sort: Merge Example

A:
1 2 3 4 5 6 7 14

k=6

L: R:
2 3 7 8 6
1 10
4 14
5 22
6

i=2 j=4
Merge-Sort: Merge Example

A:
1 2 3 4 5 6 7 8
14

k=7

L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6

i=3 j=4
Merge-Sort: Merge Example

A:
1 2 3 4 5 6 7 8

k=8

L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6

i=4 j=4
Algorithm:- Merge ( A [n], low, mid, high )
{
//A is an array of n elements, low is lower bound of
an array and high is upper bound.
1. i = low
2. j = mid + 1
3. k = low
4. Do
4.1 If( A [i] <= A [j])
4.1.1 B [k] = A [i]
4.1.2 i = i + 1
4.1.3 k = k +1
4.2 else
4.2.1 B [k] = A [j]
4.2.2 j = j +1
4.2.3 k = k +1
while (i <= mid && j <= high);
6. While ( j < = high)
6.1 B [k] = A [j]
6.2 j = j + 1
6.3 k = k +1

7. While( i <= mid )


7.1 B [k] = A [i]
7.2 i = i + 1
7.3 k = k +1

8. For (i=0 to n-1)


8.1 A [i] = B [i]

}
Implementing Merge Sort Algorithm

To understand the implementation of merge sort algorithm,


consider an unsorted list of numbers stored in an array.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

Let us sort this unsorted list.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

The first step to sort data by using merge sort is to split the list
into two parts.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

The first step to sort data by using merge sort is to split the list
into two parts.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

The list has odd number of elements, therefore, the left sublist is
longer than the right sublist by one entry.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

Further divide the two sublists into nearly equal parts.

0 1 2 2 3 3 4 4 5 5 6 6
arr 53 10
10 3030 7676 3 3 5757 24 24
Implementing Merge Sort Algorithm (Contd.)

Further divide the sublists.

0 11 22 3 3 4 45 56 6
arr 53 10
1010 3030 30
7676 76 3 357 24
57 24
Implementing Merge Sort Algorithm (Contd.)

There is a single element left in each sublist.


Sublists with one element require no sorting.

0 1 2 3 4 5 6
arr 53 10 30 76 3 57 24
Implementing Merge Sort Algorithm (Contd.)

Start merging the sublists to obtain a sorted list.

0 11 2 2 3 3 4 5
4 65 6
arr 10
53 53 10 30 30 76 76 3 357 57
24
57 24
Implementing Merge Sort Algorithm (Contd.)

Further merge the sublists.

0 1 2 2 3 3 4 4 55 6 6
arr 10 30
53 5330 7676 3 3 2457 57 57
24
Implementing Merge Sort Algorithm (Contd.)

Again, merge the sublists.

00 11 22 3 44 55 6 6
arr 10
3 30
10 53
24 76
30 533 5724 76 57
Implementing Merge Sort Algorithm (Contd.)

The list is now sorted.

0 1 2 3 4 5 6
arr 3 10 24 30 53 57 76
Write an algorithm to implement Merge sort:
Merge_sort ( A[n], low, high )
{
// A is an array of n elements,low is lower bound of
an array and high is upper bound.
1. if (low = = high)
1.1 Return Recursive Call
2. else
2.1 mid = (low + high)/2
2.2 Merge_sort ( A[], low , mid )
2.3 Merge_sort (A[], mid+1 , high )
2.4 Merge ( A[], low, mid, high )
Analysis of Merge Sort
• Divide the List into two sub-list
• Sort each sub-list
• Merge the two sub-list

The efficiency of merge sort is equal to O(n log


n)
Merge-Sort Analysis
n cn

n/2 n/2 2 × cn/2 = cn

log n levels
n/4 n/4 n/4 n/4 4 × cn/4 = cn

n/2 × 2c = cn
2 2 2

Total: cn log n

• Total running time: O (n logn)


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