A notes on Data Structures and Algorithms for computer science and engineering students, Lecture notes of Data Structures and Algorithms

ComnoteA notes on Data Structures and Algorithms for computer science and engineering students

Typology: Lecture notes

2018/2019

Uploaded on 07/27/2019

bishwas-pokharel
bishwas-pokharel 🇳🇵

4

(2)

4 documents

1 / 160

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Er. Bishwas Pokharel Page 1
A complete note on,
Data Structure and
Algorithms(CT552)
Along with the problems and solutions
By: Er. Bishwas Pokharel(Lecturer)
B.E- Pulchowk campus
MSc.Engg. -Pulchowk Campus
Published On: 2019/01/05
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download A notes on Data Structures and Algorithms for computer science and engineering students and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Er. Bishwas Pokharel Page 1

A complete note on,

Data Structure and

Algorithms(CT552)

Along with the problems and solutions By: Er. Bishwas Pokharel(Lecturer) B.E- Pulchowk campus MSc.Engg. - Pulchowk Campus Published On: 2019/01/

Er. Bishwas Pokharel Page 2

Chapter 1: Concept of Data Structure

(It is better to read chapter 1 after understanding stack ,queue, linked list) Q. Define Data Structure and its types Data structure is a particular way of organizing and storing data in a computer so that data it can be used efficiently, in term of time and space. Organization of data takes place either in main memory or in disk storage. Algorithm+ Data Structure=Program Data structure Primitive D.S Non-Primitive D.S Linear D.S Non Linear D.S Primitive D.S: These data structures are defined by system with their operation like add, sub, multiply etc. Some primitive data structures used in general programming languages are char, int, float, double etc. Non Primitive D.S: These data structures are formed by the collection of primitive data structures and for implementation it must be declared with their operation. a. Linear: stack, queue, linked list etc. b. Non Linear : tree, graph, hash map etc. Q. Explain the basic data structure operations a. Traversing: It means to access each data item exactly once so that it can be processed. For example, to print the names of all the students in a class b. Searching: It is used to find the location of one or more data items that satisfy the given constraint. Such a data item may or may not be present in the given collection of data items. For example, to find the names of all the students who secured 100 marks in the mathematics. c. Inserting: It is used to add new data items to the given list of data items. For example, to add the details of a new student who has recently joined the course.

Er. Bishwas Pokharel Page 4 Q. Write any data structure as an ADT. Stack as ADT A Stack contains elements of same type arranged in sequential order. All operations takes place at a single end that is top of the stack and following operations can be performed: a. push() – Insert an element at one end of the stack called top. b. pop() – Remove and return the element at the top of the stack, if it is not empty. c. peek() – Return the element at the top of the stack without removing it, if the stack is not empty. d. size() – Return the number of elements in the stack. e. isEmpty() – Return true if the stack is empty, otherwise return false. f. isFull() – Return true if the stack is full, otherwise return false. Q. Mention the Applications of data structure:

  1. In, Computer Network: Most of the cable network companies use the Disjoint Set Union data structure in Kruskal’s algorithm to find the shortest path to lay cables across a city or group of cities.
  2. In, Large Database Management System: creating your own database just to store the data based upon some key value, in Banks for combining two or more accounts for matching Social Security Numbers.
  3. In, Gaming: Consider graphs for example, imagine you are using Google Maps to travel from your home to office and you want to reach your office in the shortest path possible, There comes in graphs to find the shortest path using an algorithm.
  4. In, Operating System: to run various processes which enters in the FIFO manner (first in first out) i.e. whichever process enters first will move out first. To clarify it, assume you ask your system to do the following: play music, open browser, open paint then these 3 will be take as different process and will be done in FIFO manner.
  5. In, Search Engines (Google, face book …): The web crawlers in a Google search that gives you the best results at the top using the breadth first search traversal of a graph etc.

Er. Bishwas Pokharel Page 5 Q. Define an Algorithm with its example. Definition: Algorithm is a step by step instruction to solve the problems. Example: What are the steps you follow for preparing for omelet? For preparing omelet the steps we follow are as follows:

  1. Turn on the stove.
  2. Get the frying pan.
  3. Get the oil. a. Do you have oil? a. If yes, put it in a pan. b. If no, we can terminate.
  4. Etc etc.. So, what we are doing is for the given problem (preparing an omelet), giving step by step procedure for solving it. Q. Why analysis of an algorithms? To go from say, city Kathmandu to Biratnagar, there can be many ways of accomplish this: by flight, by bus, by motorcycle, by cycle, by walking and the convenience we choose the one which suits us based upon time, money, interest, urgency etc. Similarly, in computer science to solve a particular problem there are many algorithms (like insertion, merge, radix etc). So algorithm analysis helps us to determining which of them is efficient in terms of time and space consumed. So goal of analysis of an algorithm is to compare algorithms (or solution) mainly in terms of running times but also in terms of other factors (memory, developer effort etc).

d. stack[top]<-data e. stop

  1. Pop Operations: The process of extracting a data element from stack is known as pop operation. Pop operation involves a series of steps: Step 1-Checks if the stack is empty. Step 2-If the stack is empty, display stack underflow and exit. Step 3-If the stack is not empty, access the elements at which the top is pointing. Step 4-Decrease the value of top by 1 Step 5- Return success a. If top<0 then write “stack underflow and stop” b. Return Stack[top] c. top<-top- 1 d. stop Note: you can use a single linked list for the implementation and then you can indeed reduce the size of the stack when doing a pop and not just "replace" the popped element with a dummy value or create a new smaller stack and copy the rest there.(Ref: stack overflow) 2.2 What are the applications of the stack? Applications of stack:
    1. Balancing of symbols
    2. Infix to Postfix /Prefix conversion
    3. Redo-undo features at many places like editors, Photoshop.
    4. Forward and backward feature in web browsers
    5. Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem. 2.3 Infix, Postfix and Prefix notation Infix: An infix expression take, only one single letter or it has two letters with operators (+,-,,/)in between them or complete two infix expression with operators (+, - ,,/) in between them. A - > single letter

A+B - > two letters with one operator + in between them. (A+B)+(C-D) - > Two infix expression with one operator + in between them. Prefix: An prefix expression take, only one single letter or it has two letters in sequence with (+,-,,/ )before them or complete two prefix expression with operators (+, - ,,/) in between them. A - > single letter ++AB - > two letters with one operator ++ before them. ++AB-CD - > Two prefixes expression. Postfix: An postfix expression take, only one single letter or it has two letters in sequence with (+,-,,/ )after them or complete two postfix expression with operators (+, - ,,/) in between them. A - > single letter AB+ - > two letters with one operator + before them. AB+CD-+ - > Two postfixes expression. Q. Write an algorithm to convert infix into postfix expression. Algorithm:

  1. Scan the infix expression from left to right.
  2. If the scanned character is an operand, output it.
  3. Else, 3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack (or the stack is empty), push it. 3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
  4. If the scanned character is an ‘(‘, push it to the stack.
  5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
  6. Repeat steps 2-6 until infix expression is scanned.
  7. Pop and output from the stack until it is not empty. Q. Write an algorithm to evaluate the postfix expression.

WITH LESS-

PRECEDENCE

THAN –

(STACK ALWAYS

HOLD EQUAL OR

LESS OPERATOR

ON THE TOP

THAN SCAN

OPERATOR)

( CHECK AND PUSH +(-( ABC*

D +(-( ABC*D

/ CHECK AND PUSH +(-(/ ABC*D

E +(-(/ ABC*DE

^ CHECK,^ HAS

HIGHER

PRECEDENCE

+(-(/^ ABC*DE

F +(-(/^ ABC*DEF

) POP ALL

OPERATOR

UNTILL YOU

ENCOUNTER

RESPECTIVE )

+(- ABC*DEF^/

* CHECK, * HAS

HIGHER

PRECEDENCE

+(-* ABC*DEF^/

G +(-* ABC*DEF^/G

) POP ALL

OPERATOR

UNTILL YOU

ENCOUNTER

RESPECTIVE )

+ ABCDEF^/G-

* CHECK AND PUSH +* ABCDEF^/G-

H +* ABCDEF^/G-H

END POP ALL

REMAINING

OPERATORS

ABCDEF^/G-H*+

Now evaluating the expression ABCDEF^/G-H+ 2 9 3 16 4 1 ^/ 5 -8+ INPUT CHARACTER STACK OPERATION 2 2 9 2 9 3 2 9 3

  • 2 27 * OPERATOR , POP

TWO VALUES AND

PERFORM 9*3=

AND PUSH RESULT

INTO STACK

^ 2 27 16 4 4^

+ 58 (ANS) 2+56=

Note: to validate your answer check on the calculator A+(BC-(D/E^F)G)H with given value as: 2+(93-(16/4^1)5)8 then you get 58. Q. Write an algorithm to convert infix into prefix expression. Algorithm: First Reverse the input string and follows steps:

  1. Scan the infix expression from left to right.
  2. If the scanned character is an operand, output it.
  3. Else, If the precedence of the scanned operator is greater than the precedence of the operator in the stack (or the stack is empty), push it. Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
  4. If the scanned character is an ‘)‘, push it to the stack.
  5. If the scanned character is an ‘(’, pop and output from the stack until an ‘)‘ is encountered.
  6. Repeat steps 2-6 until infix expression is scanned.
  7. Pop and output from the stack until it is not empty
  8. Reverse the output string

INPUT CHARACTER STACK OPERATION

^ 8 5 4 4^1=4 (reverse than postfix) 16 8 5 4 16 / 8 5 4 16/4=

  • 8 20 4*5= 3 8 20 3 16/4= 9 8 20 3 9
  • 8 20 27 9*3=
  • 8 7 27 - 20=
  • 56 7*8= 2 56 2
  • 58 (ANS) 2+56= EXERCISE (vvi): Convert into postfix and prefix.
  1. (A+B(C+D/E)^FG) Ans: A B C D E / + F ^ * G * + prefix: +AB^+C/DEFG
  2. A+[B+C/(D/E)F]/G Ans: A [B + C D E / / F] * G / + prefix: +A+ [B/C/DE/F] G. if [ ] is used expressed in expression ELSE Ans: ABCDE//F+G/+ prefix: +A/+B/C/DEFG - > preferred this for exam
  3. A+[B+C/(D/E)$F]/G Ans: A [B + C D E / / $ * F] * G / + prefix: +A+ [B/C/DE$/F] G. if [ ] is used expressed in expression ELSE Ans: ABCDE//$F+G/+ prefix: +A/+B/C/DE$FG - > preferred this for exam
  1. Stack can be used for checking balancing of symbols. Stacks can be used to check whether the given expression has balanced symbols or not. This algorithm is very much useful in compiler. Each time parser reads one character at a time. If the character is an opening delimiter like (,{,[- then it is written to stack. When a closing delimiter is encounter like ),},]- is encountered the stack is popped. The opening and closing delimiters are then compared. If they match, the parsing of the string continues. If they do not match, the parser indicates that there is an error on the line. Algorithm: a) Create a stack. b) While(end of input is not reached){ { a) If the character read is not a symbol to be balanced, ignore it. b) If the character is an opening symbol like (,[,{, push it onto the stack. c) If it is a closing symbol like),],} then if the stack is empty report an error. Otherwise pop the stack. d) If the symbol popped is not the corresponding opening symbol, report an error. c) At end of input, if the stack is not empty report an error. By using algorithm, check validity of ()(()[()]).

a. insert 2

[0] [1] [2] [3] [4] [5] [6]

Front =0 rear =

b.Insert 5

[0] [1] [2] [3] [4] [5] [6]

Front =0 rear =

c.Insert 7,911,13,

[0] [1] [2] [3] [4] [5] [6]

Front =0 rear =

d.delete 2

[0] [1] [2] [3] [4] [5] [6]

Front =1 rear =

e.delete 5

[0] [1] [2] [3] [4] [5] [6]

Front=2 rear =

f.delete 7,9,11,

[0] [1] [2] [3] [4] [5] [6]

front =6 rear=

Algorithm for enqueue and dequeue:

a. Enqueue:

Step 1: Initialize the front = rear=-1;

Step 2: Repeat step 3 to until rear<MAXSIZE- 1

Step3: Read item

Step 4: if front==-1 then

Front=rear=

else

rear=rear+

step5: queue[rear]=item

step6: if condition of step 2 does not satisfy then print queue overflow.

b.Dequeue:

Step 1: Repeat step 2 to 4 untill front>=

Step 2: Set item=queue[front]

Step3: If front==real

Set front=- 1

Set rear=- 1

else

front=front+

step5: print deleted item

step6: print queue is empty

Note: Writing style of an algorithm may vary but concept should not be……………

Q. Explain about the linear Queue.

Linear Queue based on FIFO concept and implemented in two ways:

a. Contiguous linear queue : The queue is implemented using an array as

explained above. ( Explain enqueue and dequeue operation as described as

above).

Circular Queue : is a linear data structure in which the operations are performed based

on FIFO (First In First Out) principle and the last position is connected back to the first

position to make a circle. Graphical representation of a circular queue is as follows...

rear

front

Algorithm for Enqueue:

1. If (front ==(rear+1)%MAX) then

print “Overflow”

else:

read the value

if(front==-1)then

set front=rear=

else,

rear=(rear+1)%MAX;

q[rear]=data;

Alternative algorithm for enqueue:

Step 1:If (front==0 && rear=max-1)|| (front == rear+1)

Then write “Queue overflow “ and stop.

Step 2: Read data to insert in circular queue

Step 3: if (front = - 1) then set front=rear=

Step 4:if(rear=max-1) then rear=

else rear=rear+

Step 5: cqueue[rear]=data

Step 6: Stop

Algorithm for Dequeue:

If (front ==-1) then

print “underflow”

else:

data=q[front]

if(front==rear)then

set front=rear=- 1

else,

front=(front+1)%MAX;

Q. Define priority queue with its application.

Applications of Priority Queue:

1)CPU Scheduling

2)Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning

Tree, etc

3)All queue applications where priority is involved.

Assignment: Priority Queue

By: Er. Bishwas Pokharel, Lecturer