0% found this document useful (0 votes)
16 views4 pages

Data Structure Print

The document provides an overview of arrays, their applications, and various sorting algorithms including Bubble Sort, Insertion Sort, Quick Sort, and Merge Sort. It also discusses searching techniques such as Linear and Binary search, as well as data types in programming. Additionally, it introduces concepts like sparse matrices and abstract data types (ADT) with their advantages.

Uploaded by

wiyot41599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Data Structure Print

The document provides an overview of arrays, their applications, and various sorting algorithms including Bubble Sort, Insertion Sort, Quick Sort, and Merge Sort. It also discusses searching techniques such as Linear and Binary search, as well as data types in programming. Additionally, it introduces concepts like sparse matrices and abstract data types (ADT) with their advantages.

Uploaded by

wiyot41599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Array – An array is finite ordered collection of homogeneous data elements which provides random

access to the elements


Application of array –
Arrays are used to store list of values
Arrays are used to perform matrix operations
Arrays are used to implement search algorithm
Arrays are used to implement data structures
Arrays are used to implement sorting algorithm
Arrays are used to implement CPU Scheduling algorithms
Types of Array
One dimensional array
Multi-dimensional array - 1) Two dimensional array 2) N-dimensional array
Sparse Matrix –
A sparse matrix is two dimensional data object with m rows and n columns, therefore having m x n
element in which most of the elements have value O
Use of sparse Matrix –
Storage – There are lesser non-zero element than zeros and thus lesser memory can be used to store
only those elements
Computing time – Computing time can be saved by logically designing a data structure traversing only
non-zero elements.
Bubble sort
Algorithm: Arranging elements in ascending order)
Step 1 : Read N number of elements in the list.
Step 2 : Read array A[0], A[1]---- A[n-1]
Step 3 : For i=0 to N-1 do
For j – 0 to N-i-1 do
If (A[j] > A[j+1]) then
Temp = A[j]
A[j] = A[j+1]
A[j+1] = temp
Step 4 : stop.
To sort an array using bubble sort
#include<stdio.h>
void bubblesort (int a[],int n)
{ int i,j,temp;
for (i=0; i<n;i++)
{ for (j=0;(j<n-i-1) ;j++)
{ if (a[j]>a[j+1])
{ temp = a[j];
a[j] = a[j+1];
a[j+1] = temp; } } } }
void main ()
{int a [100], i, n ;
printf("how many element you want to short \n");
scanf("%d",&n);
printf("\n Enter the element into to the array \n");
for (i=0; i<n; i++)
scanf("\n %d",&a[i]);
bubblesort(a,n);
printf(" bubble sorted element are \n");
for (i=0; i< n; i++)
printf( " %d", a[i]); }

Insertion Sort Quick Sort


In insertion sort the element is inserted at an appropriate place. Here the array is divided into two parts It is a more popular and fastest sorting method.
sorted and unsorted sub-array. In each pass the first element of unsorted sub array is picked up and It follows the divide and conquer method i.e. numbers are divided and again subdivided and division
moved into the sorted sub array by inserting at in suitable position. goes on until it is not possible to divide further the procedure is applied recursively to the two parts of
Algorithm the array, on either side of the pivot element. It is also called partition-exchange sort.
Step 1 : Set I = 1 ; ↵ Step 2 : Key = A[i] ; ↵Step 3 : Set j = i-1 ; ↵Step 4 : If key < A[j] then This algorithm divides the input list into three main parts: 1. Elements less than the Pivot element. 2.
Pivot element (Central element). 3. Elements greater than the pivot element.
A[j+1] = A[j] ; ↵J = j-1 ↵Repeat step 2 until j> = 0 ↵Step 5 : A[j+1] = key; ↵I=i+1
Pivot element can be any element from the array, it can be the first element, the last element or any
Step 6 : Repeat step from 2 to 5 till i<n ↵Step 7 : stop random element.
Recursive Algorithm consists of four steps:
If there is one or less element in the array to be sorted, return immediately.
Pick an element in the array to serve as a "pivot" element. (Usually, the left most element in the array).
Split the array into two parts with one with elements smaller than the pivot and the other with elements
larger than the pivot.
Recursively repeat the algorithm for both halves of the original array.
Algorithm:
In the first pass, the 0th element is the pivot element.
To obtain the proper position of the pivot we traverse the list in both the directions using the indices low
and high respectively. We initialize low to that index which is one more than the index of the pivot
element (1st position).
The index low is incremented till we get an element at the lowth position greater than the pivot element.
Similarly, we initialize high to n-1 (last position) and go on decrementing high till we get an element
having the value less than the pivot element.
We then check whether low and high have crossed each other. If not then we interchange elements at
the low and high position and continue the process of incrementing low and decrementing high till low
and high cross each other.
When low and high cross each other, we interchange the pivot element and element at high position
and we find that the elements to the left of pivot element are less than it and the elements to its right
are greater than it. Hence, we get a split list. Repeat the same procedure with each sub-list.

C Program for Quick Sort


#include<stdio.h>↵#include<stdlib.h>↵void quicksort(int a[25],int first,int last)
{ int i, j, pivot, temp; ↵ if(first<last) ↵ { pivot=first; ↵ i=first; ↵ j=last;
while(i<j) ↵ { while(a[i]<=a[pivot]&&i<last) ↵ i++;
while(a[j]>a[pivot]) j--; ↵ if(i<j){ temp=a[i]; ↵
a[i]=a[j]; ↵ a[j]=temp; } } ↵ temp=a[pivot]; ↵ a[pivot]=a[j]; ↵
a[j]=temp; quicksort(a,first,j-1); ↵ quicksort(a,j+1,last); }} ↵void generate(int a[],int n)
{int i; ↵ for(i=0;i<n;i++) ↵ a[i]=rand()%100;} ↵ int main(){ ↵ int i, n, a[25];
printf("How many elements are u going to enter?: "); ↵ scanf("%d",&n);
generate(a,n); ↵ for(i=0;i<n;i++) ↵ printf("%d ",a[i]); ↵ quicksort(a,0,n-1);
printf("\nOrder of Sorted elements: "); ↵ for(i=0;i<n;i++) ↵ printf(" %d",a[i]); ↵ return 0;}
Program to implement insertion sort
#include<stdio.h> ↵# define max 20 ↵Void insertionsort (int a[max], int n) ↵
{Int i, j, key; ↵ For (i=1; i<n; i++) ↵ {Key = A[i] ; ↵For ( j= i-1; (j>=0) && (key < a[j] ; j++)
A[j+1] = a[j] ↵A[j+1] = key; }} ↵Void main ( ) ↵{ Int a[max] , i.n; ↵
Printf (“ How may element you wont to sort? \n”); ↵Scan(%d, &n);
Printf(“\n Enter the element into an array: \n”); ↵For ( i= 0; i<n; i++)
Scanf(%d. &a[i]); ↵Insertionsort (a,n); ↵Printf(“\n element after sorting: \n) ;
For (i=0; i<n; i++) ↵ Printf(“%d\t, a[i];
Merge Sort
The basic concept of merge sort is divides the list into two smaller sub lists of approximately equal size.
Recursively repeat this procedure till only one element is left in the sub list. After that, various sorted sub lists
are merged to form sorted parent list. This process goes on recursively till the original sorted list is arrived.
Algorithm for Merge Sort:
Merge sort is based on the divide-and-conquer paradigm. Its worst case running time has a lower order
of growth than insertion sort. Since we are dealing with sub problems, we state each sub problem as sorting
a sub array A[p...r]. Initially, p = 1 and r = n, but these values change as we recurse through sub problems.
1. Divide Step: If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p...r] into two sub arrays A[p...q] and A[q+1...r], each containing about half of the elements
of A[p...r]. That is, q is the halfway point of A[p...r].
2. Conquer Step: Conquer by recursively sorting the two sub arrays A[p...q] and A[q+1...r].
3. Combine Step: Combine the elements back in A[p...r] by merging the two sorted sub arrays
A[p...q] and A[q+1...r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE
(A, p, q, r).
Note: That the recursion bottoms out when the sub array has just one element, so that it is trivially sorted.
To sort the entire sequence A[1...n], make the initial call to the procedure MERGE-SORT (A, 1, n).
Merge Sort (A,p,r)

C Program for Merge Sort


#include<stdio.h>
void mergesort(int low, int mid, int high);
void msortdiv(int low, int high);
int a[50], n; ↵ void main() { ↵ int i; ↵ printf("\n Enter the n value: "); ↵scanf("%d", &n);
printf("\n Enter elements for an array: "); ↵ for (i = 0; i < n; i++) ↵{ scanf("%d", &a[i]); }
printf("\n Before sorting, the elements are: \n"); ↵for (i = 0; i < n; i++)
{printf("%d \t", a[i]); } ↵ msortdiv(0, n - 1); ↵printf("\n After sorting, the elements are: \n");
for (i = 0; i < n; i++) ↵ { printf("%d \t", a[i]); }} ↵void mergesort (int low, int mid, int high) {
int t[50], i, j, k; ↵ i = low; ↵ j = mid + 1; ↵ k = low; // Changed from 'high' to 'low'
while ((i <= mid) && (j <= high)) ↵ { if (a[i] <= a[j]) ↵t[k++] = a[i++]; ↵ else
t[k++] = a[j++]; }↵ while (i <= mid) ↵ {t[k++] = a[i++]; } ↵ while (j <= high)
{ t[k++] = a[j++]; } ↵ for (i = low; i <= high; i++) ↵ { a[i] = t[i]; }}
void msortdiv (int low, int high) ↵ { int mid; ↵ if (low < high)
{ mid = (low + high) / 2; ↵ msortdiv(low, mid); ↵ msortdiv(mid + 1, high);
mergesort(low, mid, high); } }

2.4 SEARCHING TECHNIQUES Data Types Data type is used to describe the type of data that variable may hold in the programming
Searching algorithms are used to find the element in the list. language
Two searching algorithms are: Data types in C User defined – Structure, union, enum
1. Linear search Build in – Integer, Char,float, double , void, character
2. Binary search Derived – Array, function, pointer
2.4.1 Linear Search or Sequential Search Void data Type - Void is an empty data type that has no value. This can be used in functions and
Linear search, also called as orderly search or sequential search, because every key element is pointer.
searched from first element in an array i.e a[0] to last element in an array i.e a[n-1]. User define data types
Linear search algorithm works by comparing every element in an array with the key element. If a key 1) Enum – An enumeration type is a data type that consists of integral constants. To define enums,the
element match with any element in the array, it stop search and return the location of key element in the enum keyword is used
array. 2) Structure : A structure is a tool for packing together logically related data. Items of different
It is usually very simple to implement and is practical when the list has only a few elements or when types (heterogeneous)
performing a single search in an unordered list.
3) Union : Unions are very much similar to structures. Where both are used to group number of
Algorithm for linear search:
different elements. Unlike structures, the members of union share the same storage area, even
Linear search where the result of the search is supposed to be either the location of the list item where
the desired value is found; or an invalid location to indicate that the desired element does not occur in the though the individual members may differ in types.
list. Derived Data Types
Consider array 'A' of 'n' elements need to be searched for the element 'find'. Linear_Search(A[], n, key) 1) Arrays : Assign a single name to whole group of elements (homogeneous)
Step 1: i = 0. Take the first element in the list i.e. a[i] ↵ Step 2: if(a[i] == key) then 2) Pointers : a pointers is a memory location that holds a memory address
return I ↵ Step 3 : if i<n then ↵ I=i+1 ↵ Go to step 2 ↵ Step 4 : if i=n then return -1 ↵ Step : Stop
Data Object : Data object represents a container for data values ( a place where data values may be
Program for Linear Search
stored and later retrieved)
#include<stdio.h>
Abstract data types : ADT is a mathematical model with a set of operations defined on that model
int linear_search(int [], int, int ); ↵ int main() ↵ { int a[50], key, n, position; An abstract data type includes
printf("Enter the size of elements in Array:\n"); ↵ scanf("%d", &n); ↵ 1) Domain – A Collection of data.
printf("Enter the numbers \n"); ↵ for (int i = 0; i < n; i++) ↵ { scanf("%d", &a[i]); } 2) Functions – A set of operations on the data or subsets of the data.
3) Axioms – A Set of axioms, or rules of behavior governing the interaction of operations.
printf("Enter number to search \n"); ↵ scanf("%d", &key); ↵ position = linear_search(a, n, key);
if (position == -1) ↵ { printf("%d is not present in array.\n", key); } Advantages of ADT
else { printf("%d is present at location %d.\n", key, position + 1); }
 Encapsulation
return 0; } ↵ int linear_search(int a[], int n, int key)
 Information hiding
{ for (int i = 0; i < n; i++) ↵ { if (a[i] == key) ↵ { return i; }} ↵ return -1;}  Implementation details hiding
C Program for Binary Search
 The ADT is a useful guideline to implementer and useful tool to programmers who wish to use
#include <stdio.h> ↵ int binary_search(int[], int, int, int); ↵ int main() the data type correctly
{ int a[50], n, key, result; ↵ printf("Enter the number of elements in the array:\n");  ADT is reusable and ensures robust data structure
scanf("%d", &n); ↵ printf("Enter %d elements in sorted order:\n", n); ↵ for (int i = 0; i < n; i++) ↵  Encapsulation ensures that cannot be corrupted
{ scanf("%d", &a[i]); } ↵ printf("Enter the number to search:\n"); ↵ scanf("%d", &key); Data Structure Def – A Data structure is a set of Domain D. a designed dome € D, a set of function F
result = binary_search(a, 0, n - 1, key); ↵ if (result == -1) ↵ and a set of Axioms A. The triple (D.F.A) denoted the data structure d and it will usually written as d,
printf("%d is not present in the array.\n", key); ↵ else ↵ where
printf("%d is present at position %d.\n", key, result + 1); ↵ return 0;} ↵  Domain (D) – Denotes the data objects
int binary_search(int a[], int low, int high, int key)  Function (F) – Denotes the set of operation that can be carried out on data object
{while (low <= high) ↵ { int mid = (low + high) / 2; ↵ if (a[mid] == key) ↵ return mid;  Axioms(A) – Denotes the properties and rules of operations
else if (a[mid] < key) ↵ low = mid + 1; ↵ else ↵ high = mid - 1; } ↵ return -1; } Operations of data structures
 Insertions – Insertions is used to adding a new data element in data structure
 Deletions - Deletion used to remove a data element from data structure if it is found
 Searching - Searching is used to find the location of data element in a data structure
 Traversal – Traversal of a data structure mean processing all the data elements present in it.
 Sorting – It is used to arranging data element of data structure in specified order is called sorting
 Merging – Combining element two similar data structures to form a new data structure of the
name type is called merging
Need of Data Structure 1. Space required to complete the task of that algorithm (Space complexity) it includes program
space and data space.
1) Data structures are used to study, how data are stored in a computer so that operation can be
2. Time required to complete the task of that algorithm (Time Complexity)
implemented efficiently.
Space Complexity - Total amount of computer memory required by an algorithm to complete its
2) Data structures are especially important when you have large amount of information
execution is called as space complexity of that algorithm.
3) Conceptual and concrete way to organize data for efficient storage and manipulation.
Time Complexity – The time complexity of an algorithm is the total amount of time required by
4) A Data structure helps us understand the relationship of one data element with the other.
an algorithm to complete its execution.
Advantages of data Structures Asymptotic Notation - Asymptotic notation of an algorithm is a mathematical representation of
its complexity.
1) Allows easier processing of data Types of asymptotic notations are
2) It allows information stored on disk very efficiently 1) Big-oh (O)
3) These are necessary for designing an efficient algorithm 2) Big-Omega (Ω)
4) We can access data anytime and anywhere
5) It is secure way of storage of data Big – Oh notation (o) – Big-Oh notation is used to define the upper bound of an algorithm in terms
6) Graphs module real life problems time complexity.
7) It allows processing of data on software system
 Big-Oh notation always indicated the maximum time required by an algorithm for all input values
Types of data structures
Big-Omega notation –
Data structures are divided into two types
 Linear data structures  Big-omega notation is used to define the lower bound of an algorithm in terms of time
 Non-linear data structures complexity.
Liner data structures - A data structure is said to be linear if its element form a sequence or linear list.  Big-omega notation always indicates the minimum time required by an algorithm for all input
Non Linear data structures - A data structure is said to be nonlinear if its element form a hierarchical values
classification where data items appear at various levels in this type of data structure the element don 3.2 LINKED LIST
not form sequence A linked list or one-way list is a linear collection of data elements, called nodes. Each node contains two
Difference between linear and non-linear data structure parts, first part is data and second part is link to its successor (and predecessor).
Liner data structures Non Linear data structures Linked list are classified into following three types:
In a linear data structure data element are In a non-linear data structure data element are o Linked list Singly linked list
arranged in linear order attached in hierarchically manner o Doubly linked list
In linear data structure single level is Whereas in non-linear data structure multiple o Circular linked list
involved levels are involved
Data items can be traversed in single run Data items cannot be traversed in single run  Singly circular linked list
These are easy to implement in the These are difficult to implement in the computer  Doubly circular linked list
computer memory memory as compared to implementing liner data
structure Primitive Operations on Linked List
Memory is not utilized in an efficient way Memory is utilized in efficient way Primitive operations on linked list are given as below :
Linear data structures are organized in a Non-Linear data structures are organized in a 1) Create
way to how the computer memory different way than the computer memory 2) Traverse
organized 3) Insert Node
Example – Array, Linked list, stack, and Example – Tree, Graph. 4) Delete Node
queue Few more operations are
Algorithm – 1) Searching a node
An algorithm is a finite sequence of instructions, each of which has clear meaning and can be executed 2) Updating node
with a finite amount of effort in finite time. 3) Counting length
Characteristics of algorithm Following are the characteristics of algorithm 4) Reverse the linked list
1. Input – An algorithm should accept zero or more inputs. Random number generation is an 5) Sort the linked list
example of zero input. 6) Concatenate two linked lists
2. Output – An algorithm must produce at least one result 7) Merge two sorted linked lists
3. Definiteness – Each step is an algorithm must be clear and unambiguous. This helps the one
who is following the steps to take a definite action. 3.5 SINGLY LINKED LIST
4. Finiteness – An algorithm must halt. Hence it must terminate after finite number of steps.  A linked list in which every node has one link field to provide information about where the next
5. Effectiveness – Each instruction must be sufficiently basic than it can be done exactly and in node of list is called as singly linked list.
finite time by a person using only paper and pencil  In singly linked list, we can traverse only in one direction.
 Practically, singly linked list is referred as just linked list.
Performance Analysis - Performance analysis of an algorithm is the process of calculating space The list which we have discussed till now is nothing but singly linked list. So the operations which are
required by that algorithm and time required by that algorithm. Performance analysis of an algorithm is discussed above are same.
performed by using the following measures. 3.5 DOUBLY LINKED LIST

A doubly linked list is a linear collection of data elements called nodes, where each node is having Application of stacks
three field: A pointer field which contains an address of predecessor node in the list. Expression conversion – An expression can be represented in prefix; postfix or infix notation stack
1. The data field which contains actual data like integer, float, char string value etc. can be used to convert one form of expression to another
2. A pointer field which contains the address of successor node in the list. Expression evaluation – A stack can be used to evaluate prefix postfix and infix expression
Syntax parsing – Many compliers use a stack for parsing the syntax of expressions program blacks
Singly Linked List (SLL) Doubly Linked List (DLL) etc. before translating into low level code.
Singly linked list allows us to go one way Doubly linked list has two way directions next and String reversal – stack is used to reverse a string. We push the characters of string one by one into
direction. previous. stack and then pop character from stack.
Singly linked list uses less memory per node (one | Doubly linked list uses more memory per node as Parenthesis checking – stack is used to check the proper opening and closing of parenthesis
pointer) as compare to DLL. compare to SLL Function call – stack is used to keep information about active functions or subroutines.
Complexity of Insertion and Deletion at known Complexity of Insertion and Deletion at known Recursion
position is O(n). position is O(1 A procedure is called recursive if the procedure is defined by itself for example the problem of factorial
If we need to save memory in need to update If we need faster performance in searching and can be solved using a recursive procedure
node values frequently and searching is not memory is not a limitation we use Doubly Linked Recursion is usefull in developing algorithms for specific problems the stacks is used to implement
required, we can use Singly Linked List. List. recursive procedures
In single list each node contains at least two In doubly linked list Each node contains at least In the recursion the procedure is called itself directly or indirectly. Directly means procedure called itself
parts: (a) info, and (b) link. three parts: (a) info, (b) link to next node, and (c) repeatedly. Indirect means a procedure calls another procedure. Hence the procedures or functions are
link to previous node. executed repeatedly every time a new value is passed to the recursive function till the condition
Singly linked list is unidirectional i.e., only one It is bidirectional. | satisfied
direction. If the recursive procedure call itself then values of parameters must be saved since they will be used
again when program is reactivated.
Circular linked list – C Program for Static Stack.
 A circular list is a linked in which last node points to the head node #include <stdio.h> ↵ #include <stdlib.h> ↵ #define MAX 5 ↵
 A circular list have neither a beginning nor end struct Stack { ↵ int arr[MAX]; ↵ int top;}; ↵ void initializeStack(struct Stack* stack)
 From any it is possible to reach to any other node
{ stack->top = -1; } ↵ int isFull(struct Stack* stack) ↵
S.No. ARRAY LINKED LIST
{ return stack->top == MAX - 1;} ↵ int isEmpty(struct Stack* stack)
An array is a grouping of data elements of equivalent A linked list is a group of entities called a node. The node { return stack->top == -1;} ↵ void push(struct Stack* stack, int value)
1. data type. includes two segments: data and address. { if (isFull(stack)) ↵ { printf("Stack Overflow. Cannot push %d\n", value);
return; } ↵ stack->arr[++stack->top] = value; ↵ printf("%d pushed to stack\n", value); }
It stores the data elements in a contiguous memory It stores elements randomly, or we can say anywhere in int pop(struct Stack* stack) ↵ { if (isEmpty(stack)) ↵
2. zone. the memory zone.
{ printf("Stack Underflow. Cannot pop from empty stack\n");
return -1; } ↵ return stack->arr[stack->top--]; } ↵ int peek(struct Stack* stack)
In the case of an array, memory size is fixed, and it is In the linked list, the placement of elements is allocated
3. not possible to change it during the run time. during the run time. { if (isEmpty(stack)) ↵ { printf("Stack is empty. No top element\n"); ↵ return -1; }
return stack->arr[stack->top]; } ↵ void displayStack(struct Stack* stack)
4. The elements are not dependent on each other. The data elements are dependent on each other. { if (isEmpty(stack)) ↵ { printf("Stack is empty.\n"); ↵ return; }
printf("Stack elements are: "); ↵ for (int i = 0; i <= stack->top; i++)
5. The memory is assigned at compile time. The memory is assigned at run time.
{ printf("%d ", stack->arr[i]); } ↵ printf("\n");} ↵ int main()
{ struct Stack stack; ↵ initializeStack(&stack); ↵ push(&stack, 10);
In a linked list, the process of accessing elements takes
6. It is easier and faster to access the element in an array. more time. push(&stack, 20); ↵ push(&stack, 30); ↵ displayStack(&stack);
printf("Top element is %d\n", peek(&stack)); ↵ printf("%d popped from stack\n", pop(&stack));
displayStack(&stack); ↵ push(&stack, 40); ↵ push(&stack, 50); ↵ push(&stack, 60);
Stack Definition - A stack is an ordered collection of homogeneous data elements where the insertion
push(&stack, 70); ↵ displayStack(&stack); return 0; }
and deletion operations take place at only one end called as top of stack.Stack is a set of elements in a
4.4.2.1 Algorithm to Convert an INFIX Expression to a POSTFIX Expression
last in first out (LIFO) technique The insertion or adding the element onto the stack is called push
The deletion or removing the element from the stack is called pop Primitive operations on Stack Input: Infix expression. Output: Postfix expression. ↵ Step 1: Read infix expression from left to right
Init (s) – to initialize stack ‘s’ , Push (s,x) – Push operations adds an element on the top of the stack. and character by character. Step 2: For each character 'ch' in the input string:If ch is an operand then
Top always points to the element which is recently pushed into the stack. Pop (s) – pop removes an output ch.Step 3: If ch is an operator then following action should be taken:
element which is at the top the stack after removing on topmost element the size of stack is reduce by 1 Check whether there is any operator already present in stack or not. If stack is empty then push
and the element below it becomes the top Is Empty (s) - returns true if stack is empty else return false. operator onto stack. If present then check whether priority of 1 ch is greater than priority of topmost
When is no element present on the stack then stack is said to be empty. Isfull – When top of the stack stack operator. If priority of ch is greater then push ch onto stack.
reached to stack capacity then stack is said to be full. This function returns true if stack is full else return Else pop and print operator until one of lower priority operator is encountered or the stack becomes
false. empty and finally push ch onto stack. Step 4: If ch is a left parentheses push ch into the stack.
Step 5: If ch is a right parentheses Pop and output tokens until a left parentheses is popped (but do
not output left parenthesis)
4.4.2.2 Algorithm to Convert POSTFIX Expression to an INFIX Expression Priority Queue
Input: Postfix expression. ↵ Output: Infix expression. A priority queue is a collection in which items can be added at any time, but the only item that can be
Step 1: Iterate the given expression from left to right, one character at a time. removed is the one with the highest priority
Step 2: If a character is operand, push it to stack. In some cases, the elements are inserted and deleted from any position based on intrinsic ordering
rather than stick ordering and determine which element get removed first.
Step 3: If a character is an operator, ↵ 3.1 Pop operand from the stack, say it's as s1.
Application of Queue
3.2 Pop operand from the stack, say it's as s2. ↵3.3 Perform (s2 operator s1) and push it to stack. 1) Queues are used in job scheduling by the operating system for example printer queue, process
Step 4: Once the expression iteration is completed, initialize the result string and pop out from the stack queue etc 2) Queues are used in simulation for example airport simulation to keep the track of
and add it to the result. 1 problem like number of plane processed. 3) Handing of interrupts in real time system the
Step 5: Return the result interrupts are handled in the same order as they arrive, first come first used. 4) To process the
4.4.5 Algorithm for Evaluation of Postfix Expression job in multiuser system queues are used 5) In batch programming to process job sequentially
Read postfix expression character by character from left to right. Step 1: If (read character = operand)
then push the element in the stack Step 2: If (read character = operator) then
(a) Pop 2 operands from the stack. Difference Between Stack and Queue
y = pop() from the stack.
x = pop() from the stack. Stack Data Structure Queue Data Structure
(b) Evaluate them by applying the operator i.e. "x operator y".
(c) Push the result onto stack. Step 3: If string is ended, pop the result. It is a linear data structure. The objects are removed or It is also a linear data structure. The objects are removed and
QUEUE inserted at the same end. inserted from two different ends.
A Queue is a linear list of elements in which data can only be inserted at one end, called the rear and
deleted from other end, called the front. The first element in a queue will be removed first from the It follows the Last In, First Out (LIFO) principle. It means that It follows the First In, First Out (FIFO) principle. It means that
queue i.e. data are processed through the queue in the order in which they are received. Therefore, the last inserted element gets deleted at first. the first added element gets removed first from the list.
queue are called First-In-First-Out (FIFO).
4.6 OPERATIONS ON QUEUE It has only one pointer- the top. This pointer indicates the It uses two pointers (in a simple queue) for reading and
A queue is an abstract data type (ADT). The operations on queue are as follows: address of the topmost element or the last inserted one of the writing data from both the ends- the front and the rear. The
1. Create (Q): Create (Q) creates an empty queue Q. stack. rear one indicates the address of the last inserted element,
2. Insert (Q, x): It adds the element x to the rear end of queue Q and returns the resulting queue. whereas the front pointer indicates the address of the first
3. Delete (Q): It deletes the element from the front end of queue Q and returns the resulting queue. inserted element in a queue.
4. IsFull (Q): It returns true if queue is full otherwise returns false.
5. IsEmpty (Q): It returns true if queue is empty otherwise returns false. Stack uses push and pop as two of its operations. The pop Queue uses enqueue and dequeue as two of its operations.
6. peek (Q): It is often used to return the value of first element without deleting it. operation functions to remove the element from the list, while The dequeue operation deletes the elements from the queue,
4.7 REPRESENTATION OF QUEUE the push operation functions to insert the element in a list. and the enqueue operation inserts the elements in a queue.
There are two ways to represent a queue in memory:
1. Static implementation of Queue (using an array) Insertion and deletion of elements take place from one end It uses two ends- front and rear. Insertion uses the rear end,
2. Dynamic implementation of Queue (using linked list) only. It is called the top. and deletion uses the front end.
Types of Queue
1) Simple Queue 2) Circular Queue 3) Priority queue A Stack data structure does not have any types. A Queue data structure has three types- circular queue,
Simple Queue – As is clear from the name itself simple queue lets us perform the operation simply i.e. priority queue, and double-ended queue.
insertion and deletion are performed likewise
Circular Queue You can visualize the Stack as a vertical collection. You can visualize a Queue as a horizontal collection.
The technique which essentially allows the queue to wrap around upon reaching the end of array,
eliminates these drawbacks. Such a technique which allows queue to wrap around from end to start is
 Null tree : A Tree with no noes is a null tree
called circular queue.
 Node : In three data structure every individual element is call as Node
Operation of circular queue
 Parent Node: The node which is an immediate predecessor of a node is called the parent node
1) Enqueue : Adding an element in the queue if there is space in the queue
of that node.
2) Dequeue : removing element from a queue if there are any element in the queue
 Child Node: In a tree data structure the node which is descendant of any node is called as child
3) Front – Get the first item from the queue
nodes
4) Rear – Get the last item from the queue
 Root Node: The topmost node of a tree or the node which does not have any parent node is
5) Isempty/isfull – checks if the queue is empty or full
called the root node.
Advantages of queue
 Leaf Node: in tree data structure The nodes which do not have any child nodes are called leaf
 Circular queue consumbes less space or memory compared to linear queue as if we delete any nodes.
element that position is used letter, because its circular  Sibling: in tree data structure Children of the same parent node are called siblings.
 It avoids shifting of queue elements  Degree of a node : in a tree data structure the total number of children of a node is called as
 Circular queues are used in application such as memory management CPU Scheduling, traffic degree of that node
system  Degree of a tree : the degree of atree is a maximum degree of the nodes in the tree in simple
words the highest degree of a node amount all the nodes in a tree is called as degree of tree.
 Level of a node: The count of edges on the path from the root node to that node. The root node
has level 0.

 Height : in a tree data structure the total number of edges from leaf node to a particular nodes in APPLICATIONS OF GRAPH
the longest path is call as height of node 1. Minimum spanning trees are useful in many applications such as in finding the least amount of
 Depth : In a tree data structure the total of edges from root node is particular node is called as dept. wire needed to connect group of computers, houses or cities.
of the node 2. To find the shortest path. For example, suppose, there are several warehouses which are
Binary tree and its types distributed over geographically distant locations. It is required to
1) Binary tree transport goods from a given warehouse to another. The various paths possible among the
2) Strictly binary tree warehouses. So it is required to find a path where the sum of the weights are minimum.
3) Complete binary tree 3. Critical path: A path of longest length in the AOE network is a critical path.
4) Full binary tree 4. Another application is coloring of map. We have to color a map so that no two adjacent
5) Perfect binary tree regions have the same color. This problem can be presented by using graph.
6) Skewed binary tree 5. The traversal of a graph like Depth First traversal has many important applications such as
7) Rotted tree finding the components of a graph, detecting cycles in an undirected graph etc.
8) Binary search tree 6. Many other problems in which graphs are used are:
Operation of binary trees (a) Topological sorting of a graph
1. Create : creating a binary tree (b) Spanning trees
2. Traversal : to visit all the nodes in a binary tree (c) Critical path finding
3. Insertion : to insert anode binary tree (d) To route from one location to other
4. Deletion : To delete a node from binary tree (e) Reliability analysis (it is an important issue in system design, manufacturer and
Binary tree traversal maintenance) or network reliability problem.
Binary tree traversal means visiting every node exactly one there are many operations Let us discuss few of the applications of graphs.
performed on tree such as insertion deletion searching a node etc for all these operation we AOV Network
need to traverse a tree a full traversal on a binary tree gives a linear ordering of the data in the A large project is subdivided into several small projects called activities. If all the activities of the
tree project are complete then the entire project is completed. In the project some of the activities are
Preorder traversal( DLR) – Data – left – right started independently. But some of the activities are started only if their previous activities are
Inorder traversal (LDR) – Left –Data-right completed. For example. Result is printed only after the marks are entered. Hence, data entry is
Post order traversal (Left – Right – Data) the previous activity of result preparation. The relationship between such a activities are
BINARY SEARCH TREE (BST) represented using directed graph. The graph has an edge (i, j) if activity i is a prerequisite for
A Binary Search Tree (BST) is a binary tree which is either empty or non-empty. If non-empty then activity j. The graph can be represent using AOV network.
every node contains a key which is distinct and satisfies the following properties: Definition of AOV Network:
1. Values less than its parent are placed at left side of parent node. A directed graph G in which the vertices represent tasks or activities and the edges represent
2. Values greater than its parent are placed at right side of parent node. precedence relations between activities is called an activity on vertex network or AOV network.
3. The left and right subtrees are again binary search trees.
Definition of Graph DFS BFS
A graph G is a set of two tuples G = (V, E), where V is a finite non-empty set of vertices and E is the set DFS stands for Depth first search BFS stands for Breadth first search
of pairs of vertices called edges. DFS visit nodes depth wise BFS visit nodes level by level
Undirected Graph:In an undirected graph, the pair of vertices representing any edge is unordered i.e. Uses stack data structure Uses Queue data structure
the pairs (v1, v2) and (v2, v1) represent the same edge. In other words the edges have no direction in DFS is faster compare to BFS BFS is slower compare to DFS
undirected graph. It requires less memory It requires more memory
Directed Graph:In a directed graph each edge is represented by a directed pair (v1, v2), v1 is the tail Backtracking is allowed Backtracking is not allowed
and v2 is head of the edge i.e. the pairs (v1, v2) and (v2, v1) are different edges. In other words the edges DFS is not optimal for finding shortest path BFS is optimal for finding shortest path
have direction in directed graph. Directed graph is also called as Digraph. Generally gets trapped into infinite loop Can never get trapped into infinite loop
1. Adjacent Vertex: When there is an edge from one vertex to another then these vertices are called
adjacent vertices. 2. Cycle: A path from a vertex to itself is called a cycle. Thus, a cycle is a path in which the
initial and final vertices are same. 3. Complete Graph: A graph G is said to be complete if every vertex in a
graph is adjacent to every other vertex. In this graph, number of edges = n(n-1)/2, where n = no. of vertices.
4. Connected Graph: An undirected graph G is said to be connected if for every pair of distinct vertices
vi, vj in V(G) there is a path from vi to vj. 5. Degree of a vertex: It is the number of edges incident to a vertex.
It is written as deg(U), where U is a vertex. 6. In-degree of a vertex: In directed graph, in-degree of a vertex
'v' is the number of edges for which 'v' is the head. 7. Out-degree of a vertex: In directed graph, the out-
degree of a vertex 'v' is the total number of edges for which 'v' is the tail. 8. Isolated Vertex: If any vertex
does not belong to any edge then it is called isolated vertex. 9. Source vertex: A vertex with in-degree zero is
called a source vertex, i.e. vertex has only outgoing edges and no incoming edges. For example, in Fig. 6.9,
'C' is source vertex. 10. Sink vertex: A vertex with out-degree zero is called a sink vertex i.e. vertex has only
incoming edge and no outgoing edge. For example, in Fig. 6.9, 'B' is sink node.11. Acyclic graph: A graph
without cycle is called acyclic graph. 12. Subgraph: A subgraph of G is a graph G' such that V(G') ⊆ V(G)
and E(G') ⊆ E(G). 13. Weighted Graph: A weighted graph is a graph in which every edge is assigned a
weight. In Fig. 6.11 weight in a graph denote the distance between the two vertices connected by the
corresponding edge. The weight of an edge is also called its cost. In case of a weighted graph, an edge is a
3-tuple (U, V, W) where U and V are vertices and W is weight of an edge (U, V).

You might also like