Module 1 Complete
Module 1 Complete
Data Structures
Module 1
1
24-02-2026
Types and Operations:
Types: Refers to the different data types used in a programming language, such as
integers, floats, characters, etc.
Operations: Involves the actions or manipulations that can be performed on these
data types, like addition, subtraction, multiplication, etc.
Data types
• The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h> Storage size for float : 4
int main(int argc, char** argv) FLT_MAX : 3.40282e+038
{ FLT_MIN : 1.17549e-038
printf("Storage size for float : %d \n", sizeof(float)); -FLT_MAX : -3.40282e+038
printf("FLT_MAX : %g\n", (float) FLT_MAX); -FLT_MIN : -1.17549e-038
printf("FLT_MIN : %g\n", (float) FLT_MIN); DBL_MAX : 1.79769e+308
printf("-FLT_MAX : %g\n", (float) -FLT_MAX); DBL_MIN : 2.22507e-308
printf("-FLT_MIN : %g\n", (float) -FLT_MIN); -DBL_MAX : -1.79769e+308
printf("DBL_MAX : %g\n", (double) DBL_MAX); 23000.000000
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
float a=2.3e4;
printf("%f",a);
return 0;
}
Iterative constructs and loop invariants
It aims to reduce complexity and make code more understandable by avoiding the
use of "goto" statements and encouraging the use of subroutines or functions.
C Loops
Loops in programming are used to repeat a block of code until the specified
condition is met.
1. Entry Controlled loops: In Entry controlled loops the test condition is checked
before entering the main body of the loop. For Loop and While Loop is Entry-
controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at
the end of the loop body. The loop body will execute at least once, irrespective
of whether the condition is true or false. do-while Loop is Exit Controlled loop.
C Loops
#include<stdio.h> OUTPUT
int main() Enter a number: 2
{ 2
int i=1,number=0;
4
printf("Enter a number: ");
scanf("%d",&number); 6
for(i=1;i<=10;i++) 8
{ 10
printf("%d \n",(number*i)); 12
14
} 16
return 0; 18
}
20
Output
#include <stdio.h>
int main()
{ OUTPUT
int a,b,c; 35 36
for(a=0,b=12,c=23;a<2;a++) {
printf("%d ",a+b+c);
}
}
Output
#include <stdio.h>
int main()
{ OUTPUT
int n;// variable declaration Enter the value of n :3
printf("Enter the value of n :"); 1 2 3 4 5 6 7 8 9 10
scanf("%d",&n); 2 4 6 8 10 12 14 16 18 20
for(int i=1;i<=n;i++) // outer loop 3 6 9 12 15 18 21 24 27 30
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Output
#include <stdio.h>
int main() { OUTPUT
int i, j, rows; Enter the value of n :5
printf("Enter the number of rows: "); *
scanf("%d", &rows); **
for (i = 1; i <= rows; ++i) ***
{ ****
for (j = 1; j <= i; ++j) *****
{
printf("* ");
}
printf("\n");
}
return 0;
}
Output
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: "); OUTPUT
scanf("%d", &rows); Enter the value of n :5
for (i = 1; i <= rows; ++i) 1
{ 12
for (j = 1; j <= i; ++j) 123
{ 1234
printf("%d ", j); 12345
}
printf("\n");
}
return 0;
}
C Loops: do while
3. It can be viewed as a
repeating if statement. The
while loop is mostly used in
the case where the number
of iterations is not known in
advance.
C Loops: while loop
while do-while
Statement(s) is executed atleast once, thereafter condition is
Condition is checked first then statement(s) is executed.
checked.
If there is a single statement, brackets are not required. Brackets are always required.
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition) do { statement(s); }
{ statement(s); } while(condition);
while and Do While
#include <stdio.h>
#include <stdio.h>
int main() {
int main()
// Write C code here
{
int a=11;
int a=11;
do
while(a==10)
{
{
printf("executed");
printf("Not executed");
printf("%d",a);
printf("%d",a);
}while(a==10);
}
return 0;
return 0;
}
}
OUTPUT:
OUTPUT:
executed
11
Structured Programming
It aims to reduce complexity and make code more understandable by avoiding the
use of "goto" statements and encouraging the use of subroutines or functions.
Loop Invariants
A loop invariant is some predicate (condition) that holds for every iteration of the
loop.
Loop invariant condition is a condition about the relationship between the variables of
our program which is definitely true immediately before and immediately after each
iteration of the loop.
For example: Consider an array A{7, 5, 3, 10, 2, 6} with 6 elements and we have to find
maximum element “max” in the array.
In the above example after the 3rd iteration of the loop max value is 7, which holds
true for the first 3 elements of array A. Here, the loop invariant condition is that max is
always maximum among the first i elements of array A.
Structured Programming
// Input
printf("Enter two numbers: "); 1. Declaration and Initialization: Variables are declared and
scanf("%d %d", &num1, &num2); initialized at the beginning of the program.
Modular design involves breaking down a program into smaller, independent modules or
functions.
Each function performs a specific task, making the code more modular and easier to
understand.
// #include <stdio.h>
• Any function can change the value of the global variable. It is available to all
the functions.
#include <stdio.h>
int main ()
{
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() =
%d\n", a); OUTPUT:
c = sum( a, b);
printf ("value of c in main() = value of a in main() = 10
%d\n", c); value of a in sum() = 10
return 0; value of b in sum() = 20
} value of c in main() = 30
int sum(int a, int b)
{
printf ("value of a in sum() =
%d\n", a);
printf ("value of b in sum() =
%d\n", b);
return a + b;
Passing Parameters: Call by Value
#include<stdio.h>
int main()
{
void change(int a)
int a=100;
{ printf("In main a= %d\n", a);
printf("In function change a=%d\n ", a); change(a);
printf("Value of a after function calling is %d", a);
a=a+100;
return 0;
printf("After adding a=%d\n",a); }
// return a;
}
24-02-2026 32
Passing Parameters: Call by Reference
#include<stdio.h>
int main()
{
void change(int *num)
int a=100;
{ printf("In main a= %d\n", a);
printf("In function change a=%d\n ", *num); change(&a);
printf("Value of a after function calling is %d", a);
(*num) += 100;
return 0;
printf("After adding a=%d\n",*num); }
// return a;
}
24-02-2026 33
Data
• Data is a collection of facts and figures or a set of values or values of a specific
format that refers to a single set of item values. It is also computer Information,
either transmitted or stored.
When Data is arranged in systematic way then it gets a structure and becomes
meaningful.
To provide an appropriate way to structure the data and produce meaningful
information we need to understand Data Structure
34
24-02-2026
• A data structure is a storage that is used to store and organize data.
• It is a way of arranging data on a computer so that it can be accessed and updated efficiently.
35
24-02-2026
Primitive Data Structure Data
• Common Operations
• Create
• Update
• Delete
Non-Primitive Data Structure
• Common Operations
• Traversal
• Insertion
• Selection
• Search
• Sort
• Merge
• Delete
Linear Data Structures
1. Static data structure: Static data structure has a fixed memory size
(allocated at compilation time). It is easier to access the elements in a
static data structure.
An example of this data structure is an array.
• Data structures where data elements are not placed sequentially or linearly
are called non-linear data structures.
• In a non-linear data structure, we can’t traverse all the elements in a single
run only.
Examples of non-linear data structures are trees and graphs.
44
24-02-2026
Non
NonLinear
LinearData
DataStructures
Structures
Non Linear Data Structures
Non Linear Data Structures
Non Linear Data Structures
Comparison
Arrays Linear Sequential Access Data Structure
• Array
• Collection of similar data elements
• Each data element is of the same data type
Given an array
• int marks[8] = {99, 67, 78, 56, 88, 90, 34, 85}
• Calculate the address of marks[4] when the base address = 1000 when
integer size is 2 bytes.
Solution
• marks[4] = 1000 + 2(4 – 0) = 1000 + 2(4) = 1008
Length of an Array
• Traverse
• Insertion
• Deletion
• Merge
• Search
• Sort
Traverse Operation
• Example
for (int i = 0; i < n; i++)
printf(“%d\n”, arr[i]);
Insertion Operation
n = 5;
pos = 6;
val = 60;
arr[pos - 1] = val;
n++;
Insertion Operation
100 104 108 112 116 120 124 128 132 136
10 20 30 40 50 60
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] arr[9]
n = 6;
pos = 3;
val = 70;
for( i = n - 1; i >= pos - 1; i--)
arr[i+1] = arr[i];
arr[pos-1] = val;
n = n+1;
Deletion Operation
100 104 108 112 116 120 124 128 132 136
10 20 30 40 50 60
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] arr[9]
n = 6;
n = n – 1;
Deletion Operation
100 104 108 112 116 120 124 128 132 136
10 20 30 40 50 60
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] arr[9]
n = 6; pos = 3;
for (i = pos - 1 ; i < n - 1 ; i++)
arr[i] = arr[i+1];
n--;
Merge Operation
• Example
int a[10] = {10, 20, 30, 40, 50};
int b[10] = {60, 70, 80};
Merge two sorted arrays
• Declaration
• data_type array_name[row_size][column_size];
• Ex: int marks[2][3];
Two-Dimensional Arrays
• Ex: Store the marks obtained by three students in five different subjects
int marks[3][5];
• Pictorial form of a two-dimensional array
Address of 2-D Array Elements
Q. 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.
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
Address of 2-D Array Elements
Q. 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.
• For example,
int marks[2][3]={90, 87, 78, 68, 62, 71};
int marks[2][3]={{90,87,78},{68, 62, 71}};
• Note:
• Only the size of the first dimension, can be omitted
• Solution
Address(A[I][J]) = BA + w{N(I – 1) + (J – 1)}
Address(marks[18][4]) = 1000 + 2 {5(18 – 1) + (4 – 1)}
= 1000 + 2 {5(17) + 3}
= 1000 + 2 (88)
= 1000 + 176 = 1176
Visualizing Array
2D Arrays 3D Arrays
Initialize 3D Array
Print Elements of 3D Array
Print Elements of 3D Array
Print Elements of 3D Array
Recursion
• Recursion is a programming #include <stdio.h>
technique where a function calls
void rec(int n) {
itself repeatedly until a specific
base condition is met. // Base Case
• A function that performs such if (n == 6) return;
self-calling behavior is known as a
printf("Recursion Level %d\n", n);
recursive function, and each
rec(n + 1);
instance of the function calling }
itself is called a recursive call.
1) Direct Recursion int main() {
rec(1);
2) Indirect Recursion return 0;
}
24-02-2026 83
Recursion
•A function that calls itself directly or indirectly is called a recursive function and
such kind of function calls are called recursive calls.
•We can solve large numbers of problems using recursion for example factorial of a
number.
Recursion
Recursion is the process which comes into existence when a function calls a
copy of itself to work on a smaller problem.
Recursion
Oops!
int result = 1;
while(result >0){
...
result++;
}
Oops!
Recursion
Oops!
Recursion
return res;
} Sum of First 5 Natural Numbers: 15
int main()
{
int n = 5;
• A stack frame is created on top of the existing stack frames each time a
recursive call is encountered and the data of each recursive copy of the
function will be stored in their respective stack.
• Once, some value is returned by the function, its stack frame will be
destroyed.
• This return point is the statement just after the recursive call.
• After all the recursive copy returned some value, we come back to the base
function and the finally return the control to the caller function.
Calculate the sum of the first N natural numbers and solve it
using recursion.
// C Program to calculate the sum of first N natural numbers using recursion
#include <stdio.h>
int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}
int res = n + nSum(n - 1);
return res;
}
int main()
{
int n = 5;
• Recursive definition:
• F(0) = 0;
• F(1) = 1;
• F(number) = F(number-1)+ F(number-2);
Fibonacci numbers
int fibonacci (int n)
#include<stdio.h> {
int fibonacci(int); if (n==0)
{
void main ()
return 0;
{ }
int n,f; else if (n == 1)
{
printf("Enter the value of n?"); return 1;
scanf("%d",&n); }
f = fibonacci(n); else
{
printf("%d",f); return fibonacci(n-1)+fibonacci(n-2);
} }
}
int display (int n) Recursion
{
if(n == 0)
return 0; // terminating condition
else
{
printf("%d",n);
return display(n-1); // recursive call Let us examine this recursive function for n = 4.
}
}
What is Searching Algorithm?
Searching Algorithms are designed to check for an element or retrieve an element from any
data structure where it is stored.
Based on the type of search operation, these algorithms are generally classified into two
categories:
Sequential Search: In this, the list or array is traversed sequentially and every element is
checked. For example: Linear 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.
How Does Linear Search Algorithm Work?
Every element is considered as a potential match for the key and checked for the same.
If any element is found equal to the key, the search is successful and the index of that element
is returned.
If no element is found equal to the key, the search yields “No match found”.
For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30
How Does Linear Search Algorithm Work?
Time Complexity
Best Case O(1)
Average Case O(n)
Worst Case O(n)
•Divide the search space into two halves by finding the middle index “mid”.
•Compare the middle element of the search space with the key.
•If the key is not found at middle element, choose which half will be used as the next search space.
•If the key is smaller than the middle element, then the left side is used for next search.
•If the key is larger than the middle element, then the right side is used for next search.
•This process is continued until the key is found or the total search space is exhausted.
Binary Search: Iterative Approach
• An ideal data structure could be the one that takes least possible time for all of its
operations and consumes the least memory space.
24-02-2026 109
Time Complexity
Inserting data at the start of array
24-02-2026 110
Time Complexity
Inserting data at the start of linked list
24-02-2026 111
Time Complexity
24-02-2026 112
Time Complexity
24-02-2026 113
Cont…
Finding F(N)
Cont…
Example:
Cont…
Example:
Cont…
Example:
Cont…
Example:
Cont…
Example:
Asymptotic Notations
• The commonly used asymptotic notations used for
calculating the running time complexity of an
algorithm is given below:
• Big Oh Notation (O)
• Omega Notation (Ω)
• Theta Notation (θ)
Big Oh Notation (O)
• Big Oh notation provides an upper bound on a
function which ensures that the function never
grows faster than the upper bound.
• gives the least upper bound on a function
• i.e. the function never grows faster than this
upper bound
• It is the formal way to express the upper boundary of
an algorithm running time.
• It measures the worst case of time complexity or the
algorithm's longest amount of time to complete its
operation.
Table relating size of data set to amount of computations
24-02-2026 124
Cont…
Example: Program to Calculate Sum of First N Natural Numbers
Cont…
Example: Program to Calculate Sum of First N Natural Numbers
Sorting
• Sorting
• Refers to arranging data in a particular format
• Sorting algorithm
• Specifies the way to arrange data in a particular order
• Importance of sorting lies
• Data searching can be optimized to a very high level, if data is stored in a
sorted manner
• Used to represent data in more readable formats
• Real-life scenarios
• Telephone Directory
• Dictionary
In-place and Not-in-place Sorting
• Sorting algorithms may require some extra space for comparison and
temporary storage of few data elements
• In-place sorting
• do not require any extra space and sorting is said to happen in-
place
• for example, within the array itself
• Bubble sort, insertion sort, selection sort, quick sort, heap sort is an
example of in-place sorting
• Stable Sorting
• Sorting does not change
the sequence of similar
content in which they
appear (eg. Bubble sort,
insertion sort, merge
sort, etc.)
return 0;
}
Sorting: Bubble sort
• Comparison-based algorithm
• Works on the repeatedly swapping of adjacent elements until they are not in
the intended order.
• Called bubble sort
• The movement of array elements is just like the movement of air
bubbles in the water
• Average and worst case complexity are of Ο(n2) where n is the number of
items
• Not suitable for large data sets
• Used
• Complexity does not matter
• Simple and short code is preferred
Sorting: Bubble sort
• Time Complexity
1. Best Case Complexity
• Occurs when there is no sorting required, i.e. the array is already
sorted
• The best-case time complexity of bubble sort is O(n)
2. Average Case Complexity
• Occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending
• Average case time complexity of bubble sort is O(n2)
3. Worst Case Complexity
• Occurs when the array elements are required to be sorted in reverse
order
• The worst-case time complexity of bubble sort is O(n2)
Sorting: Selection Sort
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element from the unsorted portion of the list and
moving it to the sorted portion of the list.
Sorting: Selection Sort
Sorting: Selection Sort
Sorting: Selection sort
#include <stdio.h> void printArr(int a[], int n) /* function to print the array */
void selection(int arr[], int n) {
{ int i;
int i, j, small; for (i = 0; i < n; i++)
for (i = 0; i < n-1; i++) printf("%d ", a[i]);
{ }
small = i;
for (j = i+1; j < n; j++) int main()
{ {
if (arr[j] < arr[small]) int a[] = { 31,12,0 , 25, 8, 32, 17 };
{ int n = sizeof(a) / sizeof(a[0]);
small = j; printf("Before sorting array elements are - \n");
} printArr(a, n);
} selection(a, n);
int temp = arr[small]; printf("\nAfter sorting array elements are - \n");
arr[small] = arr[i]; printArr(a, n);
arr[i] = temp; return 0;
} Output: }
}
Before sorting array elements are -
31 12 0 25 8 32 17
After sorting array elements are -
0 8 12 17 25 31 32
Sorting: Selection sort
• Time Complexity
1. Best Case Complexity
• Occurs when there is no sorting required, i.e. the array is already sorted
• The algorithm still performs the full number of comparisons to confirm the
array is sorted, resulting in O(n²) time complexity
2. Average Case Complexity
• Occurs when the array elements are in jumbled order that is not properly
ascending and not properly descending
• On average, the number of comparisons remains the same, leading
to O(n²).
3. Worst Case Complexity
• Occurs when the array elements are required to be sorted in reverse order
• The maximum number of both comparisons and swaps, but the number of
comparisons is still bound by O(n²).
Insertion Sort
Algorithm
• Step 1- If the element is the first element, assume that it is already
sorted. Return 1
• Step2- Pick the next element, and store it separately in a key
• Step3- Now, compare the key with all elements in the sorted array
• Step 4- If the element in the sorted array is smaller than the current
element, then move to the next element. Else, shift greater elements in
the array towards the right.
• Step 5- Insert the value
• Step 6- Repeat until the array is sorted
Insertion Sort
Insertion Sort
void insertionsort()
{
for (int i=1; i<n;i++)
{
int j=i-1;
int key=arr[i];
while(j>=0 && key<=arr[j])
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
Insertion Sort
• Time Complexity
• Best Case Complexity
• Occurs when there is no sorting required, i.e. the array is already
sorted
• The best-case time complexity - O(n)
• Average Case Complexity
• Occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending
• Average case time complexity - O(n2)
• Worst Case Complexity
• Occurs when the array elements are required to be sorted in reverse
order
• The worst-case time complexity - O(n2)
Divide-and-Conquer
172
Merge Sort
1 2 3 4 5 6 7 8
Divide 5 2 4 7 1 3 2 6 q=4
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
174
Merge Sort
1 2 3 4 5 6 7 8
Conquer 1 2 2 3 4 5 6 7
and
Merge 1 2 3 4 5 6 7 8
2 4 5 7 1 2 3 6
1 2 3 4 5 6 7 8
2 5 4 7 1 3 2 6
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
175
Merge Sort
p q r
1 2 3 4 5 6 7 8
Alg.: MERGE-SORT(A, p, r) 5 2 4 7 1 3 2 6
MERGE-SORT(A, p, q) Conquer
MERGE-SORT(A, q + 1, r) Conquer
MERGE(A, p, q, r) Combine
176
Merging
p q r
1 2 3 4 5 6 7 8
2 4 5 7 1 2 3 6
177
Merging
p q r
• Idea for merging: 1 2 3 4 5 6 7 8
A1 A[p, q]
A[p, r]
A2 A[q+1, r]
178
Example: MERGE(A, 9, 12, 16)
p q r
179
Example: MERGE(A, 9, 12, 16)
180
Example (cont.)
181
Example (cont.)
182
Example (cont.)
Done!
183
Merge - Pseudocode
Alg.: MERGE(A, p, q, r) p q r
1. Compute n1 and n2
1 2 3 4 5 6 7 8
2 4 5 7 1 2 3 6
2. Copy the first n1 elements into
L[1 . . n1 + 1] and the next n2 elements into R[1 . . n2 + 1] n1 n2
1. L[n1 + 1] ← ; R[n2 + 1] ←
2. i ← 1; j←1 p q
3. for k ← p to r L 2 4 5 7
4. do if L[ i ] ≤ R[ j ] q+1 r
5. then A[k] ← L[ i ] R 1 2 3 6
6. i ←i + 1
7. else A[k] ← R[ j ]
8. j←j+1
184
Merge Sort
void merge(int arr[], int l, int m, int r){ while (i < n1 && j < n2) {
int i, j, k; if (L[i] <= R[j]) { // Copy the remaining elements of
int n1 = m - l + 1; arr[k] = L[i]; R[], if there are any
int n2 = r - m; i++; while (j < n2) {
} arr[k] = R[j];
// Create left & right array else { j++;
int L[n1], R[n2]; arr[k] = R[j]; k++;
j++; }
// Copy data to L[] and R[] } }
for (i = 0; i < n1; i++) k++;
L[i] = arr[l + i]; }
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j]; // Copy the remaining elements
of L[], if there are any
// Merge array L and R back into while (i < n1) {
arr[l..r] arr[k] = L[i];
i = 0; i++;
j = 0; k++;
k = l; }
Merge Sort
• Time Complexity
• Best Case Complexity
• Occurs when array is already sorted
• Best-case time complexity - O(n*log n)
• Average Case Complexity
• Occurs when the array elements are in jumbled
order
• Average case time complexity - O(n*log n)
• Worst Case Complexity
• Occurs when the array elements are required to be
sorted in reverse order.
• Worst-case time complexity - O(n*log n)
Quicksort
< 28 <
1. Pick a “pivot”
2. Divide into less-than & greater-than pivot
3. Sort each side recursively
The steps of QuickSort
S1 S2 partition S
0 31 75
43 65
13 81
92
26 57
QuickSort(S1) and
S1 S2 QuickSort(S2)
0 13 26 31 43 57 65 75 81 92
S 0 13 26 31 43 57 65 75 81 92 Presto! S is sorted
[Weiss]
The steps of QuickSort
QuickSort Example
i j
5 1 3 9 7 0 4 2 6 8
i j
5 1 3 9 7 0 4 2 6 8
i j
5 1 3 9 7 0 4 2 6 8
i j
5 1 3 2 7 0 4 9 6 8
5 1 3 2 7 0 4 9 6 8
i j
5 1 3 2 7 0 4 9 6 8
i j
5 1 3 2 4 0 7 9 6 8
i j
5 1 3 2 4 0 7 9 6 8
j i
5 1 3 2 4 0 7 9 6 8
j i
0 1 4 2 4 5 6 9 7 8
while (i <= j)
{
while (i <= high && arr[i] <= pivot)
i++;
if (i < j)
swap(&arr[i], &arr[j]);
}
The steps of QuickSort
Quick sort:
• pick a pivot value from the array
• partition the list around the pivot value
• sort the left half
• sort the right half
Merge sort:
• divide a list into two identically sized halves
• sort the left half
• sort the right half
• recombine the sorted halves into a sorted whole
Quick Sort
• Time Complexity
• Best & Average Case Complexity
• Occurs when the pivot consistently divides the array
into roughly equal halves.
• Best-case time complexity - O(n*log n)
• Worst Case Complexity
• Happens with already sorted/reverse-sorted data or
poor pivot selection (like always picking the
smallest/largest element), creating highly
unbalanced partitions .
• Worst-case time complexity - O(n2)
24-02-2026 201