Docsity

A Complete note on data structures and algorithms, Exams of Data Structures and Algorithms

Partial preview of the text

Download A Complete note on data structures and algorithms and more Exams Data Structures and Algorithms in PDF only on Docsity!

BEST OF LUCK!!

Data Structures and

Algorithms

A complete note

By Bishwas Pokharel(068/BCT/515) Pulchowk Campus

1. Concept of Data Structure

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. An example of common data structures are: array, stack, queue, linked list, tree, hash map etc. 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. To simplify the process of solving problems, these data structures are combined with their operation and are called Abstract Data Types. An ADT consist of two parts:

  1. Declaration of data
  2. Declaration of operations Commonly used ADT are: Linear: stack, queue, linked list etc. Non Linear: tree, graph, hash map etc. For Ex: 1.1 lntroduction: data types, data structures and abstract data types

b. If no, we can terminate.

  1. Etc etc.. So, what we are doing is for given problem (preparing an omelet), giving step by step procedure for solving it. Algorithm is a step by step instruction to solve the problems. 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). Q. what is the running time analysis? It is the process of determining how processing time increases as the size of problem ( input size increases). In general we encounter following types of inputs: Size of an array, Number of elements in matrix, Vertices and edge in graph, Polynomial degree etc. Q. How to compare algorithms? To compare algorithms, let us define few objective measures: Execution times? Not a good measures as execution times are specific to a particular computer. Number of statements executed? Not a good measure, since the number of statements varies with the programming language as well as the style of the individual programmer. Ideal solution? We expressed running time of given algorithm as function of the input size n (f(n)) and compare these different functions corresponding to running times. This kind of comparison is independent of machine time, programming styles, etc. Rate of growth: The rate at which the running time increases as a function of input is called rate of growth. Let us assume you went to a shop for buy car and a cycle. If your friend sees you there and asks what are you buying then in general we say buying a car. This is because, cost of car is too big compared to cost of cycle.

Total Cost = cost_of_car + cost _of_cycle. Total cost nearly equal to cost_of_car(approx..) For the above example, we can represent the cost of car and cost of cycle in terms of function and for given function ignore the low order terms that are relatively insignificant. For Ex: if n^4 , 2n^2,110n, 500 are individual costs of some function and approximate it to n^4 is the highest rate of growth. Running time in term of function:

  1. for(i=1;i<=n;i++) //executes n times m=m+1; // for 1 execution say, take constant time c for 1 execution take c time, for n execution take cn time, so, total running time :f(n)=cn 2 .for(i=1;i<n;i++){ //outer loop executed n times for(i=1;i<n;i++){ //inner loop executed n times k=k+1; // for 1 execution say, take constant time c } } for 1 execution take cn time, for n execution take cn*n time, so, total running time : f(n)= cn^ Types of analysis: To analyze given algorithm we need to know on what inputs the algorithm is taking less time (performing well) and on what inputs the algorithm is taking huge time. Best case: Algorithm takes less time. Input is one for which algorithm runs the faster. Worst case: Algorithm takes huge time. Input is one for which algorithm runs the slower. Average case: Lower Bound<= Average Time <= Upper Bound An algorithm may run faster on some inputs than it does on others of the same size. Thus we may wish to express the running time of an algorithm as the function of the input size obtained by taking the average over all possible inputs of the same size. However, an average case analysis is typically challenging.

Ex: f(n)=3n+8 is O(n) Solution: 3n+8 <=(3n+n) <=4n f(n)<=cg(n), for c =4 and n0>= 8

2. Big Omega-Ω notation: Let f(n) and g(n) be functions mapping nonnegative integers to real numbers. We say that f(n) is Ω(g(n)) (pronounced "f(n) is big-Omega of g(n)") if there is a real constant c > 0 and an integer constant n0 >= 1 such that f(n) >= cg(n), for n >= n0. 3. Big-Theta-ʘ notation: f ( n ) is Θ( g ( n )) (pronounced " f ( n ) is big-Theta of g ( n )") if f ( n ) is O( g ( n )) and f(n) is Ω( g ( n )), that is, there are real constants c 1 > 0 and c 2 > 0, and an integer constant n 0 >= 1 such that c 1 g ( n ) <= f ( n ) <= c 2 g ( n ), for n >= n 0. By:BishwasPokharel(068/BCT/515),Pulchowkcampus

2. The Stack and Queue

2.1 Stack operation

Q. How stacks are used? Consider a working day in the office. Let us assume a developer is working on a long-term project. The manager then gives the developer a new task, which is more important. The developer places the long-term project aside and begins work on the new task. The phone rings, this is the highest priority, as it must be answered immediately. The developer pushes the present task into the pending tray and answers the phone. When the call completes the task abandoned top answer the phone is retrieved from the pending tray and work progress. A stack is an ordered list in which insertion and deletion are done at one end, where the end is called as top. The last element inserted is the first one to be deleted. Hence, it is called Last IN First Out(LIFO) list. When an element is inserted in a stack, the concept is called as push and when an element is removed from the stack, the concept is called as pop. Trying to pop out an empty stack is called as underflow and trying to push an element in a full stack is called as overflow.

Implementation in C++:

2. Pop Operations: The process of putting a new data element onto 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, produces an error 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. Algorithms: 1. If top<0 then write “stack underflow and stop” 2. Stack[top]<-Null 3. top<-top- 1 4. stop Implementation in C++

#include using namespace std; #define MAX 1000 class Stack { int top; public: int a[MAX]; //Maximum size of Stack Stack() { top = - 1; } void push(int x) { if (top >= MAX) { cout << "Stack Overflow"; } else { a[++top] = x; } } int pop() { if (top < 0) { cout << "Stack Underflow"; } else { int x = a[top--]; } } bool isEmpty() { return (top < 0); } void stack_content() { for(int i=0;i<=top;i++) { cout<<a[i]<<" "; } } };

2.2 Stack application: Evaluation of lnfix, Postfix and Prefix expressions

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 indicate that thers 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 ()(()[()]).

2.Infix to postfix conversion algorithm using stack. 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. Algorithm:

**1. Scan the infix expression from left to right.

  1. If the scanned character is an operand, output it.
  2. 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.

Evaluate the postfix Expression: Algorithms:

  1. If an operand is encountered, push it on stack.
  2. If an operator ‘op’ is encountered. a. Pop two elements of stack, where A is the top element and B is the next top element b. Evaluate B op A. c. Push the result on stack.
  3. The evaluated value is equal to the value at the tip of the stack. Ex1. 5 ,9, 8, +, 4, 6, *,+,7,- Ans: 170 Ex1. 7,2, – , 1, 3 , + ,/ Ans: 5/ **Infix to prefix conversion algorithm using stack. Algorithm: First Reverse the input string and follows steps:
  4. Scan the infix expression from left to right.
  5. If the scanned character is an operand, output it.
  6. 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.

  1. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
  2. Repeat steps 2-6 until infix expression is scanned.
  3. Pop and output from the stack until it is not empty b. Reverse the output string** Ex: 23/(2-1)+5(4-1) Solution: +/23-215- 41 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 Operations in queue, Enqueue and Dequeue

Queue: A Queue is an ordered list in which insertions are done at one end (rear) and deletions are done at other end (front). The first element inserted is the first one to be deleted. Hence, it is called First IN First Out (FIFO) list. A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.

Algorithms for dequeue operations: Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation − Step 1 − Check if the queue is empty. Step 2 − If the queue is empty, produce underflow error and exit. Step 3 − If the queue is not empty, access the data where front is pointing. Step 4 − Increment front pointer to point to the next available data element. Step 5 − Return success. procedure dequeue if queue is empty return underflow end if data = queue[front] front ← front + 1 return true end procedure Implementation of queue When we remove element from Queue, we can follow two possible approaches (mentioned [A] and [B] in above diagram). In [A] approach, we remove the element at head position, and then one by one move all the other elements on position forward. In approach [B] we remove the element from head position and then move head to the next position.

In approach [A] there is an overhead of shifting the elements one position forward every time we remove the first element. In approach [B] there is no such overhead, but whenever we move head one position ahead, after removal of first element, the size on Queue is reduced by one space each time.

2.4 Linear and circular queue

Circular Queue: In a normal Queue Data Structure, we can insert elements until queue becomes full. But once if queue becomes full, we cannot insert the next element until all the elements are deleted from the queue. For example consider the queue below...