0% found this document useful (0 votes)
4 views

DS Week 3 Lecture Structure Pointer DMA Recursion ToH by DR Gaurav

Uploaded by

titirshaasingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DS Week 3 Lecture Structure Pointer DMA Recursion ToH by DR Gaurav

Uploaded by

titirshaasingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Subject: Data Structure

Using C++ (CSET243)

Week 3 Lecture

Structure, Pointer, DMA, Recursion,


Binary Search, Tower of Hanoi
What, Why and How?

by

Dr Gaurav Kumar
Asst. Prof, Bennett University
Quick Recap of Last Week’s Learnings

• Asymptotic Notations

• Algorithm & Time Complexity Analysis

• Analysis of Various Operations of 1D and 2D Arrays

• Visualized the Linear Searching Algorithm


Assessment Time

1. What is an algorithm?

a) A specific software program

b) A set of instructions designed to perform a specific task

c) A programming language

d) A type of computer hardware

Answer: b) A set of instructions designed to perform a specific task


Assessment Time

2. Which of the following is NOT a characteristic of a good

algorithm?

a) Finite steps

b) Infinite loops

c) Well-defined inputs

d) Produces a correct output

Answer: b) Infinite loops


Assessment Time

3. What will be the output of the following code?

int a = 5;

cout << a++ << " " << ++a;

a) 5 6
b) 5 7
c) 6 7
d) 6 6
Answer: b) 5 7
Quick Recap of Visualization of Searching Algorithms

01 Linear Search

02 Binary Search
Visualization of Linear Search

8 3 1 2 4 5 6 7
Algorithm of linear search

Key Element = 4 Step 1- Start from the leftmost element of arr[] and one

Total Number of Comparison = 5 by one compare x with each element of arr[].

Step 2- If x matches with an element, return the index.

Key Element = 7
Step 3- If x doesn’t match with any of the elements,
Total Number of Comparison = 8 return -1.
Visualization of Linear Search

8 3 1 2 4 5 6 7

Time Complexity Analysis

Searching the key element present at the first index of a list

Key Element = 8
Total Number of Comparison = 1
f(n) = 1 = Constant = O(1)

Best Case Time Complexity


Visualization of Linear Search

8 3 1 2 4 5 6 7

Time Complexity Analysis

Searching the key element present at the last index of a list

Key Element = 7
Total Number of Comparison = 7

for n elements f(n) = n

Worst Case Time Complexity


f(n) = O(n)
Visualization of Linear Search

8 3 1 2 4 5 6 7

Time Complexity Analysis


Searching the key element present at any random index of a list

Key Element = 8 or 3 or 1 or 2 or 4 or 5…

Total Avg Time = All possible case time divided by number of cases

Average Case Time for n elements Average Time= (1+2+3+...n)/n = n(n+1)/2n = n+1/2
Complexity Avg Case Time Complexity
f(n) = O(n)
Quick Recap of Visualization of Searching Algorithms

2. Binary Search
• Binary search is a fast way to find an item in a sorted list.

• It follows the divide and conquer approach in which the list is divided into
two halves, and the item is compared with the middle element of the list.

• If the match is found then, the location of the middle element is returned.
Otherwise, we search into either of the halves depending upon the result
produced through the match.
Visualization of Searching Algorithms

2. Binary Search
Visualization of Binary Searching Algorithms

1. Divide the search space into two halves by finding the middle index

“mid”.

2. Compare the middle element of the search space with the key.

3. If the key is found at middle element, the process is terminated.

4. If the key is not found at middle element, choose which half will be used as the next search space.

1. If the key is smaller than the middle element, then the left side is used for next search.

2. If the key is larger than the middle element, then the right side is used for next search.

5. This process is continued until the key is found or the total search space is exhausted.
Time Complexity of Binary Searching Algorithms

(Iterative Method Approach)


int binarySearch(int[] A, int x)
{
int low = 0, high = A.length - 1;
1. Divide the search space into two halves by finding the middle index “mid”.
while (low <= high)

2. Compare the middle element of the search space with the key. {

int mid = (low + high) / 2;


3. If the key is found at middle element, the process is terminated.
if (x == A[mid])
4. If the key is not found at middle element, choose which half will be used as the {
return mid;
next search space.
}
1. If the key is smaller than the middle element, then the left side is used for else if (x < A[mid]) TC= O(logn)
next search.
{
high = mid - 1;
??
2. If the key is larger than the middle element, then the right side is used for }
else
next search. {

5. This process is continued until the key is found or the total search space is low = mid + 1;
}
exhausted. }
return -1;
}
Visualization of Time Complexity of Binary Searching Algorithm

TC= O(logn) Number of Elements


(Superscript)
Number of Times Mid Comparison

2 1 ---------→ 21
4 2 1 ---------→ 22
8 4 2 1 ---------→ 23
16 8 4 2 1 ---------→ 24
32 16 8 4 2 1 ---------→ 25
64 32 16 8 4 2 1 ---------→ 26
128 64 32 16 8 4 2 1 ---------→ 27
. .
.
. .
.
.
.
.
.
N …………………. ---------→ 2k

We know that: N= 2K Log2N = K. Log2 2


Apply Log2 both side,
K = LogN
Log2N = Log2 2K

Animated Image Source: Pinjee.com


Time Complexity of Binary Searching Algorithm

Best Case Time Complexity of Average Case Time Complexity


Binary Search: O(1) of Binary Search: O(logN)

Worst Case Time Complexity Space Complexity of Binary


of Binary Search: O(logN) Search: O(1) (for iterative)
Auxiliary Space
Structure struct [structure tag]
{
member definition;
member definition;
...
} [one or more structure variables];

Title • Structure is another user defined data type that allows to


Author combine data items of different kinds.
Subject
Book ID • Structures are used to represent a record. It helps us to
keep track of our books in a library.
Structure
Each variable in the structure is known as a member of the structure.

struct [structure tag] struct Books {


{ char title[50];
char author[50];
member definition;
char subject[100]; Title
member definition;
int book_id; Author
...
Subject
member definition; }book1, book2;
or Book ID
} [one or more structure variables];
struct Books book1; //declaration of variables
struct Books book2;
Visualization of Structure Variables

struct Books { struct Books book1; //declaration of variables

char title[50];
book1
char author[50]; char title[50]; | (50 bytes)

char subject[100]; char author[50]; | (50 bytes)

int book_id; char subject[100]; | (100 bytes)

}; int book_id; | (4 bytes)

Total Space: 204 bytes 2000


Accessing Structure Variables

struct Books { struct Books book1, book2; //another way


char title[50];
Book1.title= “Data Structure";
char author[50];
char subject[100];
Book1.author=“Yashwant Kanetkar";
int book_id;
}book1, book2; Book1.subject= “DS Tutorial";

Book1.book_id = 6495407;

cout<< "Book 1 title : %s\n", Book1.title”;


cout<< “Book 1 author : %s\n", Book1.author”;
Structure as a Function Argument
struct Books { /* function declaration */
char title[50]; void printBook( struct Books book );
char author[50];
char subject[100];
int book_id; /* function definition */
}; void printBook( struct Books book)
{
cout<<"Book 1 title : %s\n", book.title;
cout<<"Book 1 author : %s\n", book.author;
}
Pointer
A pointer is a variable whose value is the address of another variable, i.e., it
stores the direct address of the memory location.

type *var-name; //syntax of pointer variable declaration

int *ip;

double *dp;

float *fp;

char *ch ;
Pointer
A pointer stores the direct address of the variable, or it points to the memory
location of variable.

int var1 = 100;


int *ptr ; //pointer to an integer
ptr= &var1; //store the address of int variable
cout<<ptr; //print the address of var1
cout << *ptr; // Output: 10 (value stored at the address in ptr)
* is also used as dereferencing.
Applications of Pointer

❖ Accessing memory directly.

❖ Pointers are crucial for managing memory dynamically, especially in

situations where the size of data is not known in advance.

❖ Efficient array and structure handling.


Pointer to an Array

Array and Pointer Relationship:


arr[0] arr[1] arr[2]
• Arrays and pointers are closely related.
arr 1 2 3
int arr[3] = {1, 2, 3}; 2000 2004 2008

cout<<arr;
ptr
(arr indicated the base address of array)

int* ptr = arr; // ptr points to the first element of arr

(the array name acts as a pointer to the first element)


Pointer to an Array

Array and Pointer Relationship:


arr[0] arr[1] arr[2]
• Arrays and pointers are closely related.
arr 1 2 3
int arr[3] = {1, 2, 3}; 2000 2004 2008

int* ptr = arr; // ptr points to the first element of arr

Pointer Arithmetic
ptr

cout << *(ptr + 1);


// Output: 2 (Accessing the second element)
Pointer to an Array
Array and Pointer Relationship:
arr[0] arr[1] arr[2]
int arr[3] = {1, 2, 3}; arr 1 2 3
2000 2004 2008
int* ptr = arr; // ptr points to the first element of arr

arr[0] we can write as *ptr ptr Ptr+1 Ptr+2

arr[1] we can write as *(ptr+1)

arr[2] we can write as *(ptr+2)


Applications of Pointer
❖ Pointers allow functions to modify variables outside their scope.

Example: Swapping of Two Numbers (Normal Approach)


int main()
{
int a = 5, b = 10, temp;
cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl;
return 0; }
Applications of Pointer
❖ Pointers allow functions to modify variables outside their scope.

Example: Swapping of Two Numbers (using Function)


x y
void swap(int a, int b) int main() 5 10
{ {
int temp = a; int x = 5, y = 10;
a = b; swap(x, y);

b = temp; cout << "x = " << x << ", y = " << y;

} b } x y
a
Output? ? ?
10 5
Applications of Pointer
❖ Pointers allow functions to modify variables outside their scope.

Example: Swapping of Two Numbers (using Function)


x y
void swap(int a, int b) int main() 5 10
{ {
int temp = a; int x = 5, y = 10;
a = b; swap(x, y);

b = temp; cout << "x = " << x << ", y = " << y;

} b } x y
a
Output: 5 10
10 5

Note: When Swap function is called, it creates a local copy of variables, and scope of the variable is till function alive.
the actual value of variables in the main function will remain unchanged.
Applications of Pointer
❖ Pointers allow functions to modify variables outside their scope.

Example: Swapping of Two Numbers (using Pointer Approach)


x y
void swap(int *a, int *b) int main() 5 10
{ {
temp 2000 4000
int temp = *a; int x = 5, y = 10;
*a = *b;
2000 swap(&x, &y);//passing address of variable x & y

*b = temp; 6000 cout << "x = " << x << ", y = " << y;

} b } x y
a
Output: 10 5
2000 4000

8000 12000
Pointers to Structures
struct Books { struct Books *struct_pointer;
char title[50];
char author[50]; struct_pointer = &book1;
char subject[100];
int book_id;
}book1, book2;

To access the members of a structure using a pointer to that structure, you must use
the → operator as follows

struct_pointer->title;
In Normal Structure
cout<< "Book title :“ << struct_pointer->title; book.title
Extended Pointer (Pointer to Pointer or Double Pointers)
int a, *b, **c; a
a=10;
10 b
b=&a;
c=&b; 2000 2000
c
cout<<"The value of a is : “<< a; 4000
4000
cout<<"The value of b is : “<< *b ;
7000
cout<<"The value of c is : “<< **c;

Output: 10, 10, 10


Assessment Time
int a, *b, **c; a
a=10;
**c 20
10
b=&a; b
c=&b; 2000
**c=20; 2000
cout<<"The value of a is : “<< a;
c
4000
Output: 4000
(A) 10
(B) 20 7000
(C) 30
(D) Error

Correct Answer is B
Assessment Time
int a, *b, **c; a
a=10;
*b **c 30
10
b=&a; b
c=&b; 2000
**c=a + 2*(*b); 2000
cout<<"The value of a is : “<< a;
c
4000
Output: 4000
(A) 10
(B) 20 7000
(C) 30
(D) Error

Correct Answer is C
Returning a Pointer (Assessment Time)

int* fun() main() p


A
{ { Address
10 of A ??
int A = 10; int* p;
5000 2000
return (&A); p = fun();
} }
Address
of A
Output ??
Note: Scope/Life of a Variable is
limited to the Local Function only Segmentation Error
Returning a Pointer

int* fun() main()


{
{
int* p;
static int A = 10;
p = fun();
return (&A);
}
}
Pointer - Homework

Explore the different


operations on Pointer
Dynamic Memory Allocation (DMA)

• Memory Allocation: Refers to the process of reserving memory space


during program execution.

Types

• Static Memory Allocation: Memory size is determined at compile time.

• Dynamic Memory Allocation: Memory is allocated during runtime.


Why DMA ?

• Flexibility in memory usage.

• Efficient use of memory.

• Allows the creation of data structures like linked lists, trees, etc., which

require dynamic resizing.


How we create DMA ?

• Using new and delete Operators

• new Operator: Allocates memory on the heap and returns a pointer to it.

• delete Operator: Deallocates memory previously allocated with new.


How we create DMA ?

• Allocating Arrays Dynamically

int* arr = new int (5); // Allocating array of 5 integers

for(int i = 0; i < 5; i++)


{
arr[i] = i + 1;
}

delete[] arr; // Deallocating memory


How we create DMA (Pointer & Structure)?

• Allocating Structure Variables Dynamically

struct Node { Data


next
(10)
int data; ptr
Node* next; 2000 2000
};

Node* ptr = new Node; cout << ptr->data; delete ptr;


// Output: 10 // delete the allocated
ptr->data = 10;
memory
Explore More about DMA

Self Study
Recursion

A function calling itself is called recursion &


corresponding function is called as recursive
function.

T (n) = T(n-1) + n

Unstructured
Recursion

fact(int n)
{
if (n < = 1) // base case or stopping condition
return 1;
else
return n*fact(n-1);
}
Unstructured
Visualization of Recursion
Example - Sum of first n natural numbers

Approach(1) - Simply adding one by one Approach(2) – Recursive adding

Sum(n) = n+ sum(n-1) Algorithm Sum (n)


Algorithm Sum (A, n)
Sum (5) = 5+4+3+2+1 {
{
Sum (5) = 5 + Sum(4) if(n==1)
S=0;
Sum (4) = 4 + Sum(3) return 1;
for ( i=0; i<n; i++)
Sum (3) = 3 + Sum(2) else
{ return n + sum(n-1);
Sum (2) = 2 + Sum(1)
S= S + A[i]; }
Sum (1) = 1
}
return S; Unstructured
}
Visualization of Recursion
Example - Sum of first n natural numbers Sum(n) = n+ sum(n-1)

Algorithm Sum (n) Sum (5) Total = sum(5) =15;


{ return 15
return 5 + Sum(4)
if(n==1)
return 10
return 1;
return 4 + Sum(3)
else
return 6
return n + sum(n-1); return 3 + Sum(2)
}
return 3
return 2 + Sum(1)
return 1
Unstructured return 1
What does recursion relation mean

1 if n=1 Base/Stopping Condition


Sum (n) =
Sum(n-1) + n if n>1

A recurrence relation is an equation or inequality that describes a function in terms of its values on
smaller inputs.

Used to reduce complicated problems to an iterative process based on simpler versions of the
problem

Unstructured
T(n) term is used to define the time complexity in recurrence relation analysis.
Writing Recurrence Relations
Example- Analyze the time complexity of this algorithm

Algorithm Demo(n) T(n)


{
If (n>0) 1 if n=0
{ T (n) =
T(n-1) + 1 if n>0
Print “ n”; 1
Demo(n-1); T(n-1)
}
} Unstructured

T(n)= T(n-1) + 1
Writing Recurrence Relations
Example - Sum of first n natural numbers

Algorithm Sum (n) T(n)


{
1 if n=1
if(n==1)
T (n) =
return 1; 1 T(n-1) + n if n>1

else
return n + sum(n-1); n + T(n-1)
}

Unstructured
Solving Recurrence Relations

There are four methods for solving Recurrence Problems

Back Substitution/ Iteration Method

Recursion Tree Method

Master Method

Substitution Method

Note:
• Please self read these topics.
• Detail of these topic will be covered in the course Design and analysis of Algorithms (Next Semester)
Self Practice Problem using Recursion

Tower of Hanoi Problem


There are three towers, 3 disks, with decreasing sizes, placed on the first tower. You need to move
all of the disks from the first tower to the last tower, A large disk can not be placed on top of a
smaller disk. The remaining tower can be used to temporarily hold disks
Self Practice Problem using Recursion

Tower of Hanoi Problem

• How many operations needed to transfer 7 disks from source tower


to destination tower?

• Given that 10 disks can be moved in 1023 operations, how many


operations needed for 11 disks?
Self Practice Problem using Recursion

Tower of Hanoi Problem

• How many operations needed to transfer 7 disks from source tower


to destination tower?

• Given that 10 disks can be moved in 1023 operations, how many


operations needed for 11 disks?
Explore Sorting Algorithms
Explore the Sorting Algorithms

• Stable and In-Place Sorting Algorithms

• Bubble

• Selection

• Insertion Sort

• Merge Sort
Any Queries?

Office MCub311
Discussion Time: 3-5 PM
Mob: +91-8586968801

You might also like