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

Module 3

DSA notes for beginners

Uploaded by

Amit Motaphale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

Module 3

DSA notes for beginners

Uploaded by

Amit Motaphale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 25
Lecture Notes Data Structures and Applications [21CS35] Recursion It isa process in which an object is defined in terms of simpler case of itself. Direct Recursion A function which calls itself repeatedly is called recursive function. Ex: a (formal parameters) { a (arguments); Note: The important requirements or constraints that every recursive function should satisfy are Y Every time a function is called, it should be nearer to the solution, Y There should be at least one statement to terminate recursion, The recursive function calls are initially pushed on to the stack until the terminating condition is met, After encountering the terminating condition the recursive functions are popped from the stack and executed. Dr.Mahesh G Dr.Harish G ‘Assoc. Prof, Assoc. Prof BMSIT & M Dr. Al Indirect Recursion A recursive function need not call itself directly. Rather, it may contain a call to another function which eventually calls the first function and both are termed recursive. Ex: a (formal parameters) b (formal parameters) { { b (arguments); a (arguments); Here function ‘a’ calls “b’, which may in tum call ‘a’, which may again call ‘b’, Thus both ‘a’ and ‘b’ are recursive, since they indirectly call on themselves, However the fact that they are recursive is not evident from examining the body of either of the routines individually. Module 3 1 Lecture Notes Data Structures and Applications [21CS35] Example 1: Factorial Function Given a positive integer ‘n’, n! is defined as the product of all integers between ‘n’ and 1. The exclamation mark (!) is often used to denote the factorial function. Ex: 5! = 5x4x3x2x1 3! 3x2x1 ol=1 ‘The recursive definition to find the factorial of ‘n’ 1 if(n =0) fact(n) = fa—=0)| - n* fac(n—1) otherwise Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Pro. Ex: To compute 4! BMSIT-€ M beat 4l=4x3! I=1x0! Recursive Program to find the factorial of a number /*Function to find factorial of a number*/ int fact(int n) { if(n= = 0) return 1; return(n*fact(n-1)); } void main( ) { int n, result; print{(“enter the value of n\n"); scanf(“Sed”, &n); result = fact(n); printf(‘“factorial of ed ded\n”, n, result); Module 3 Lecture Notes Data Structures and Applications [21CS35] Example 2: Fibonacci Sequence The Fibonacci sequence is the sequence of integers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, The first two numbers 0 and 1 are the initial values. The n'™ Fibonacci number is the sum of the two immediate preceding elements. The recursive definition to find the n' Fibonacci number is given by 0 a=) Fib(n) = 1 if(n==2) Pib(n 1) + Pib(n—2) otherwise ‘The recursive tree for fib(5) is as shown below Fib(5) 3 —. —— Fib(4) Fib(3) 2 1 L oN. . U™. Fib(3) + — Fib(2) Fib(2) + — Fib(1) 0 a! 1 1 \ Fib(2) + Fib(1) 1 ° Recursive Program for Fibonacci number int fib(int n) t Dr.Mahesh G Dr.Harish G ift 1) Assoc, Prof, Assoc, Prof. return 0: BMSIT aM De AT if(n==2) return 1; return(fib(n-1)+ fib(n-2)); Function to find the n' void main( ) { int n, result; printf(“enter the value of n\n”); scanf(“%d”, &n); result = fib(n); printf(* Ged fibonacci number = %d\n", n, result); Module 3 3 Lecture Notes Data Structures and Applications [21CS35] Main Function to generate ‘n’ Fibonacci numbers void main( ) { int n, i printf(“enter the value of n\n"); scanf(“%d”, &n); print{(“The fibonacci numbers are\n”); Example 3: GCD (Greatest Common Divisor) ‘The GCD of two numbers 'm' and 'n' denoted by GCD(n n) is defined as the largest integer that divides both 'm' and ‘n’ such that the remainder is zero. Example: To find GCD(10, 30) DrMahesh G DrHarish G ‘The numbers 1,2,5 and 10 can divide 10. Assoc. Prof, Assoc. Prof BMSIT & M Dr. AFT The numbers 1,2,3,5,6,10, 15 and 30 can divide 30. and 10. The Greatest Common Divisor (GCD) is 10 ‘The recursive definition to find GCD of two numbers 'm' and 'n' is given by m if ) GCD(m.n) = { GCD(m=n,n)_ if(m>n) lecoomn—m if(m n) return GCD(m-n, n); if(m #include int count = 05 Module 3 7 Lecture Notes Data Structures and Applications [21CS35] void tower(int n, char source, char destination, char temp) { printf("move %d dise from %c to Gec\n"sn,source,destination); count++; return; } tower(n-I, source, temp, destination); printf("move %d dis from %c to oc\n",n,source,destination); ‘count++; tower(n-I, temp, destination, source); } void main( ) { int n; elrser(); printf(“enter the number of discs\n"); seanf("%d" &n)3 tower(n, SDT); printf("the total number of dise moves=%d" count); geteh( )s } Example 6 Ackerman’s Function In computability theory, the Ackermann function, named after Wilhelm Ackermann, is one of the simplest and earliest-discovered examples of a total computable function. The Ackermann, function is a classic recursive example in computer science. It is a function that grows very quickly (in its value and in the size of its call tree). It is defined as follows: nel ifon=0)) amn=| Amin gaol Dr-Mahesh G Dr-Harish G Atm LAr) otters pee | oe To see how the Ackermann function grows so quickly, it helps to expand out some simple expressions using the rules in the original definition, For example, we can fully evaluate A(1,2) in the following way: A(1,2) Module 3 8 Lecture Notes Data Structures and Applications [21CS35] ‘To demonstrate how A(4,3)'s computation results in many steps and in a large number: A(4,3) = A(3, A(4,2)) = A(3,A(3, A(4,1))) A(3, Al A(3,Al A(3, 2 ppp a ES i EN A(3,A A(3, A A(3, A A AQ, A A(3, A A(3, A AQ, A A(3,A AQ, A A(3, A A(3,/ AG, A(3, 65533)) AS 33) 65596 =e -3. Module 3 A(3,A(4,0)))) 3,A(3, 1)))) A(2, 4 A(2, 4 A(2, A(3,A(2, 3,A(2, A(2,/ A(2,/ A(2, A(2, 3,4(2, (3,0))))) 2,1))))) - -A(a,4)))) +400, 4(1,0))))))) »4(0, A(0,1))))) +4(0,2)))))) )))) A(1,2)))))) A(0, A(1,1))))))) A(0, A, A(1,0)))))))) ,4(0, 4(0, A(0, 1)))))))) A(0, A(0,2)))))) A(0,3))))) _ Se: Dr.Mahesh G Dr.Harish G Assoc. Prof, Assoc. Prof. BMSIT & M Dr. AIT Lecture Notes Data Structures and Applications [21CS35] Recursive Program for Ackerman’s Function int ackerman(int m, int n) { if(m== 0) return n+1; if(n==0) return (ackerman(m-1,1)); return(ackerman(m-1, (ackerman(m, n-1)))); } Dr.Mahesh G Dr.Harish G void main( ) ‘Assoc. Prof. Assoc. Prof. { BMSIT & M De. AIT int m, n, result; printf(“enter the value of m\n”); seanf(“%d”, &m); printf(“enter the value of n\n”); seanf(%d”, &n); result = ackerman(m, n) printi(‘ackerman(%d, %ed) = %d\n”, m, n, result); Module 3 10 Lecture Notes Data Structures and Applications [21CS35] Queues Basic Operations ‘A queue is basically a waiting line, for example, a line of customers in front of a counter in a bank or a ticket counter. Here, Y Customers join the queue at the end of line (rear or tail). ¥ Customer who is at the front gets the service and leaves the line (front or head). This indicates that a customer gets service in FCFS (First Come First Serve) or FIFO (First In First Out) basis, As a data structure, a queue is an ordered list of elements from which an element may be removed at one end called front of the queue, and into which an element may be inserted at the other end called the rear of the queue. These restrictions ensure that data are processed through the queue in the order in which they are received. So a queue is also called FIFO data structure. Pictorial representation of the queue is as shown below. o 123 4 5 delete — [10] 20[30 ]— Insert Tt tT f r The various types of queues are Y Ordinary queue Y Double ended queue Y Circular queue Y Priority queue Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. awit &M or AT Queue Abstract Datatype Objects: A finite ordered list with zero or more elements Funetions: For all q € Queue, item € element, queuesize € positive integer Queue Create(queuesize) = Creates an empty queue whose maximum size is queuesize Boolean IsFull(q, queuesize) _:= if number of elements in queue q is queuesize return TRUE else return FALSE Quewe InsertQ(q, item) (UsFull(q) queue is full else insert item on to the queue q and return Boolean IsEmpty(q) = iff no elements are there in queue return TRUE else return FALSE Element DeleteQq) = if (sEmpty(q)) return else remove and return the element at the front ofthe queue Module 3 u Lecture Notes Data Structures and Applications [21CS35] Ordinary Queue or Linear Queue or Queue ‘This queue operates on a first come first serve basis. Items will be inserted from one end and they are deleted at the other end in the same order in which they are inserted. The various operations that can be performed on a ordinary queue are 1. Insert Rear ~ Here elements are inserted from rear end of the queue. 2. Delete Front — Here elements are deleted from the front end. 3. Display — Here contents of queue are displayed Observations ¥ Initially when there are no elements f= 0 and r= -1 Y Whenever f > r there are no elements in the queue i.e. the queue is empty. Y f=rmeans there is only one element in the queue, Implementation of Queues using arrays #include Hdefine queuesize 5 void insert_rear(int item, int *r, int q[]) { if(*r = = queuesize-1) { printf(“queue overflow\n"); return; } fetal Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. ql*t] = item; eMsiT & M or. AIT } void delete_front(int *f, int *r, int q[]) { int item; iff > *1) { printf(“queue is empty\n"): return; } item = ql*f printf("\nthe item deleted is %d" item); f= hl; iff > *) { *£=05 *ra-l; } } Module 3 12 Lecture Notes Data Structures and Applications [21CS35] void display(int f, int r, int qf) { int is if(f > 9) { printf(“queue is empty\n"); return; } printf("the contents of the queue are\n"); for(i=fs ist; i++) { printf("%d\n" qliDs } } void main() { int f,r, choice, item, q[30}s elrser(); eA Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. for(3) MST Ma var { printf("\n1 :insert_rear\n2:delete_front\n"); printf("3:display\n4: exit\n"); printf("enter your choice\n"); seanf("Zed" ,Scchoice); switeh(choice) { case 1: printf("enter the item to be inserted\n"); scanf("%ed" ,Scitem); insert_rear(item, &r, q)s break; case 2: delete_front(&t, &r, q)s break; case 3: display(f, r, qs break; case 4: exit(0); } getch( ); } } Module 3 13 Lecture Notes Data Structures and Applications [21CS35] Disadvantages of ordinary queues ‘The disadvantage of ordinary queue is that once rear reaches (queuesize -1 ) it is not possible to insert any element into the queue even though the queue is not full. This situation is depicted in the following figure. 0123 4 delete — 30 [40] 50] — Insert T T queuesize f r Even though there are 2 free locations, since the value of r has reached queuesize ~ 1, we will not be able to insert rear Solution 1: Shift data to previous locations such that the elements start from the beginning of the queue. This method proves to be costly in terms of computer time if the data being stored is very large, Solution 2: Use circular queue to overcome this situation. Dr.Mahesh G Dr.Harish G . Assoc. Prof. Assoc. Prof. Circular Queue syst a Dr. arr As the name suggests, this queue is not straight but circular; meaning, the last element of the array is logically followed by the first element of the array (element with index 0). It has a 3] a (0) // Initially r = -1 and f= 0 (2) q{l] After inserting 4 elements and then deleting 2 elements we have the queue structure as shown structure as shown below below. Module 3 14 Lecture Notes Data Structures and Applications [21CS35] If we try to insert an element to the queue we follow 2 steps ¥ Increment rear pointer. Y Insert item to q[ ] pointed by rear. Since this is a circular queue, once rear pointer reaches the end position the next one will be the first position. To attain this we use the statement r= (r+ 1) % queuesize EX:(341)% 4% 4 =0 (first position) If this approach is used, to check for queue overflow and underflow, we use a variable called as ‘count’, Count contains the number of items or elements present in the queue at any instant. Therefore, count = 0 means the queue is empty and count = queuesize means the queue is full. Note: 1. Ina queue (circular or linear), if we want to insert we follow insert rear and if we want to delete we follow delete front. 2. When an item is inserted and if rear points to the last position, we ¢ \sert one more item if and only if the queue does not contain any item in the first position, otherwise it will be queue overflow state 3. Fora circular queue to Y Insert we follow r=(r+1) % queuesize q{r] = item count = count + 1 ‘Assoc. Prof, Y Delete we follow oMsiT aM. Dr.Mahesh G Dr.Harish G item = q[fl f=(f+1) % queuesize count I count Y Queue empty and full we follow count = 0 for queue is empty count = queuesize for queue is full Module 3 15 Lecture Notes Data Structures and Applications [21CS35] Implementation of circular queues using arrays #include define queuesize 5 void insert_rear(int item, int *r, int *count, int q{) { if(count = = queuesize) { printf(queue overflow\n"); return; } r= (*r+1) % queuesizes ql*r] = item; *count = *count + 13 } void delete_front(int *f, int *count, int q[]) { int item; Dr.Mahesh G Dr.Harish G if(*count = = 0) pent a eee { printf("queue is empty\n"); return; } item = q[*f]; printf("\nthe item deleted is %d" item); #f = (#E+1) % queuesizes *count = *count - 13 } void display(int f, int count, int ql) { int i; if(count { ) printf(“queue is empty\n"); return; } printf("the contents of the queue are\n"); for(i=1si<=count;i++) { printf("%ed\n" q(t); f= (+1) % queuesizes Module 3 16 Lecture Notes Data Structures and Applications [21CS35] void main() { int f, r, choice, item, q[5], count; elrser()3 £=05 r=-l count = 05 for(;;, { printf("\n 1 sinsert_rear\n2:delete_front\n"); printf("3:display\n4:exit\n"); printf("enter your choice\n"); Dr.Mahesh G Dr.Harish seant"Zea &choice); peace switch(choice) BMSIT & M. Dr. AIT { case I: printf("enter the item to be inserted\n"); seanf("%d" item); insert_rear(item, &r, &count, q); break; case 2: delete_front(&f, &count, q); break; case 3: display(f, count, q)s break; case 4: exit(0); } getch( ); } Applications of Queues ¥ One major application of queue is in simulation which is studied as queuing theory in ‘operation research. The main objective of this simulation is to study the real life situation (problem) under the control of various parameters (waiting time, input flow rate, servicing time etc) which affects the queuing problem. Y Queues are used in time sharing systems in which processes form a queue while waiting to be executed. Y They are used in network communication systems. Y They are used in operating system to handle i/o request, while waiting for a specific device to get the service. Module 3 17 Lecture Notes Data Structures and Applications [21CS35] Circular Queues using Dynamic Arrays (with the concept of array doubling) In this case just doubling the array size is not sufficient because as ordering of elements and re-initialization of front and rear pointers need to be done. For example consider a circular queue with queue size 5, after inserting 5 elements the structure is as shown below. oO 1 2 3 4 at) [0 [20 7304050 t Queue is full f r After deleting 3 elements we obtain the following structure, O12 3 4 Dr.Mahesh G Dr.Harish G 40150 Assoc. Prof. ASSOC. Prof 7 NSIT & M Or Ar one Now insert 3 elements into the queue we get the following structure. o 12 3 4 at | [60 [70] 80 [40 [50] count = queuesize = 5 1 T Queue is full rf AC this point, just doubling the array size is not sufficient, the elements need to be copied in correct order, and the front and rear pointers need be re-initialized appropriately, newgI | [40 [50 | 60 [ 70 | 80 void delete_front(int *f, int *count) { int item; if(count = = 0) { printf("queue is empty\n"); return; } item = q{*f]s printf("\nthe item deleted is %d" item); *f = (#41) % capacity; *count = *count - 13 } Module 3 18 Lecture Notes Data Structures and Applications [21CS35] void insert_rear(int item, int *r, int *count, int *f) { int i; int *newg; // to create new queue if(count = = capacity) { // Allocate memory to double the array capacity newg = (int*) malloc 2 * capacity * sizeof(int)); /1 Copy the elements from old queue to new queue for(i=0;i Delete <— Insert 2) Output Restricted De-queue An Output Restricted De-queue is one which allows the deletion at only one end, but allows insertions at both ends. Example: Deletion possible only at front end oO 1 2 3 4°55 Insert — [1020730 — Insert Delete « The operations that can be performed on a De-queue are 1) Insert Front 2) Insert Rear Dr.Mahesh G Dr.Harish G 3) Delete Front ‘Assoc. Prof. Assoc. Prof. 4) Delete Rear BMSiT & M Or. AIT 5) Display Note: insert_rear( ), delete_front() and display( ) functions same as that of ordinary queue. Function to insert an element at the front end Case 1: o 123 45 (ao [20730 Insertion Not Possible f r f=Oandr!=-1 Case 2: -l o123 4°55 Insertion Possible r f r=r¢+1 ale] = item Case 3: o12 3 4 30 | 40. Insertion Possible ror f=f-1 lf] =item Module 3 21 Lecture Notes Data Structures and Applications [21CS35] void insert_front(int item, int *f, int *r, int qf]) { if(*f ==0 && *r !=-1) { printf("Insert front not possible\n"); return; } re"; ql*r] =item; return; } } an element at the rear end void delete_rear(int *f, int *r, int q{]) DeMaheanG Detiatan @ { Assoc. Prof. Assoc. Prof. int item; eMsiT Mt Or A iff > *1) { printf(“queue is empty\ return; } item = ql*r]; printf("\nthe item deleted is %d",item); retry ifr > *) { Module 3 22 Lecture Notes Data Structures and Applications [21CS35] Priority Queues In linear and circular queues the operations are performed according to FIFO approach. Sometimes, we may need to process items according to their importance in their appli In such a situation, priority queues can be used. Priority queue is a queue in which each element of the queue will have a priority and the elements are processed (insertion and deletion) according to the following rules. 1) An element of higher priority is processed before any element of lower priority 2) If 2 elements have same priority, then the element which was inserted to the queue will be processed first Dr.Mahesh G Dr.Harish G Assoc. Prof. Asso«. Prof. esr am Or. AMT ‘Types of Priority Queues 1) Ascending Priority Queue It is a collection elements where elements can be inserted in any order but while deleting, the smallest element is to be removed from the queue. 2) Descending Priority Queue It is a collection elements where elements can be inserted in any order but while deleting, the largest element is to be removed from the queue. Priority Queue Implementation Two methods have been described below for implementing priority queue using arrays. Here items to be inserted itself denotes the priority. It is assumed that smaller value element has higher priority and larger value element has smaller priority i.e. 3 has higher priority when compared to 5, Method - 1 Here the aim is to © Insert elements in any order * Delete only the smallest element (High priority element) ‘The deletion signifies that it is an ascending priority queue and is performed as shown below Step 1: Starting from front, traverse the array to find the smallest element (High priority element) and its position. Step 2: Delete this element from the queue. Step 3: If necessary (deleted element is not the right most), shift all its trailing element to left side by one position after the deleted item to fill the vacant position and update the rear pointer. Module 3 23 Lecture Notes Data Structures and Applications [21CS35] Function to delete the smallest element for implementing priority queue void delete_small(int *f, int *r, int q]) { int item, i, min, pos; if(*f > *r) { printf("queue is empty\n")s return; } } Dr.Mahesh G Dr.Harish G else Assoc. Prof. Assoc. Prof { ows & ear all: ise ry i++) if(qli] < min) { } } item = q[pos}; printf("\nthe item deleted is %ed" item) for(i=pos; is*r: i++) { alil =alittk } Sr=4r- ly } } Note: The other functions i.e inser_rear( ), display() and main( ) remains same as that of ordinary queue. Disadvantage very inefficient as it involves searching the queue for smaller element and shifting the trailing elements after deletion, Module 3 24 Lecture Notes Data Structures and Applications [21CS35] Method - 2 Here the aim is to # Insert elements into queue such that they are always ordered in increasing order (ascending order) i.e. high priority elements are at the front end always. Step 1: Find an appropriate vacant position to insert based on item priority. Step 2: Insert the item at that position, Step 3: Update the rear pointer. * Simply delete an element from the front end since the smallest element will always be in the front, Fun n to insert an element for implementing priority queue void insert_order(int item, int *f, int *r, int q[]) it int j; if(#r = = queuesize-1) { printf("queue is full\n"); return; “ry while( j >= *f && item < qlj]) { ali+1] = afi. j=l: J Dr.Mahesh G Dr.Harish G qlit1] = item; ‘Assoc. Prof. Assoc. Prof. Sra fred; OMSIT aM Dr. AIT J Note: The other functions ie delete_front( ), display( ) and main( ) remains same as that of ordinary queue, Disadvantage * Insertion requires locating the proper position for the new element and also requires shifting of element: * Insertion needs to do compaction, when it runs out of memory space left but cannot insert). Note: In general, arrays are not efficient for implementing priority queues. Module 3 25

You might also like