ece ds notes 2010 new

117
Data Structures and Algorithms SMVEC SRI MANAKULA VINAYAKAR ENGINEERING COLLEGE MADAGADIPET AFFILIATED TO PONDICHERRY UNIVERSITY EC T33 - DATA STRUCTURES AND ALGORITHMS Questions and Answers II Year - III Semester ELECTRONICS AND COMMUNICATION ENGINEERING Page 1

Upload: naveen-raj

Post on 10-Mar-2015

365 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

SRI MANAKULA VINAYAKAR ENGINEERING COLLEGE

MADAGADIPET

AFFILIATED TO PONDICHERRY UNIVERSITY

EC T33 - DATA STRUCTURES AND ALGORITHMS

Questions and Answers

II Year - III Semester

ELECTRONICS AND COMMUNICATION ENGINEERING

Syllabus

Page 1

Page 2: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

EC T33 - DATA STRUCTURES AND ALGORITHMS

UNIT – I

Introduction to data structures: Information and meaning – Arrays in C – Structures in C

Stack: Definition and examples – Representing stacks in C – Infix, postfix and

prefix

UNIT – IIRecursion:

Recursive definition and processes – Recursion in C – Writing recursive programs – Simulating recursion – Efficiency of recursion.Queues and Lists:

The queue and its sequential representation – Linked Lists – Lists in C– Simulation using linked lists – Other list structures.

UNIT – IIITrees:

Binary trees – Binary tree representations – Huffman algorithm – Representing lists as binary trees – Trees and their applications – Game trees.

UNIT – IVSorting:

General background – Exchange sorts – Selection and tree sorting – Insertion sorts – Merge and radix sortsSearching:

Basic search techniques – Tree searching – General search trees - Hashing

UNIT – VGraphs and their applications:

Graphs – A flow problem – Linked representation of graphs – Graph traversal and spanning forestsStorage management:

General lists – Automatic list management – Dynamic memory management.

Page 2

Page 3: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Unit-1

Unit-1

Part-A

1. What is data structure?A data structure is a way of organizing data that considers not only the items stored,

but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.

2. List out the areas in which data structures are applied extensively?Compiler Design,Operating System,Database Management System,Statistical analysis package,Numerical Analysis,Graphics,Artificial Intelligence,Simulation

3. What are the major data structures used in the following areas RDBMS, Network data model & Hierarchical data model.

RDBMS – Array (i.e. Array of structures)Network data model – GraphHierarchical data model – Trees

4. What is a pointer?Pointer is a variable, which stores the address of the next element in the list. Pointer

is basically a number

5. Define Data Structure and its types A data structure is a way of organizing data that considers not only the items

stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data. Types:

Primitive / Non-Primitive Homogeneous / Heterogeneous Static / Dynamic Linear / Non-Linear

6. Define Primitive Data Structure

Page 3

Page 4: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Primitive data structures are basic data structure and are directly operated upon machine instructions, e.g., integer, character, strings

7. Define Non-Linear Data Structure Non-linear data structures do not maintain any linear relationship between

their elements, e.g. Tree and Graphs.

8. What is meant by an abstract data type?An ADT is a set of operation. Abstract data types are mathematical

abstractions. Eg.Objects such as list, set and graph along their operations can be viewed as ADT's.

9. What are the operations of ADT?Union, Intersection, size, complement and find are the various operations of ADT.

10. Give some examples for linear data structures?1. Stack2. Queue

11. Define Dynamic Data structure.It becomes possible to allocate old storage when it is needed and to discard old

storage when it is needed during the program of execution.

12. Define Static Data Structure.It becomes to fixed amount of storage must be pre allocated, remain through correct

the execution of the program.

13. List the operation performed by the data structure.

Operating to create and destroy a data structureInsert element into the data structureDelete elements from to data structureAccess elements with in a data structure.

14. Define list.A list is an ordered set containing of a variable with number of elements to which insertion and deletion can be made.

15. Define an array?An array is a group of logically related data items of the same data – type addressed

by a common name and all items are stored in contiguous memory.

16. Difference between array and list.

Page 4

Page 5: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

An array is an ordered set which consists of a fixed number of objects. No deletion or insertion operations are performed on array.A list is an ordered set, consisting of a variable number of elements to which insertion and deletion can be made.

17. Write down the uses of array?a) The array is a powerful tool that is widely used in computing.b) Arrays provide us with a very simple efficient way of referring to and perform

computations on collections of data that share some common attribute.c) Arrays can be used to build and simulate finite state automata.

18. What is a stack?Stack is a data structure in which both insertion and deletion occur at one end only.

Stack is maintained with a single pointer to the top of the list of elements. The other name of stack is Last-in -First-out list.

19. What is the data structures used to perform recursion?

Stack. Because of its LIFO (Last In First Out) property it remembers its ‘caller’ so knows whom to return when the function has to return.

Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function.

Even when such equivalent iterative procedures are written, explicit stack is to be used.

20. What are the various Operations performed on the Stack? 1) push 2) pop 3) peek

21. How do you test for an empty stack?The condition for testing an empty stack is top = 0.

22. Name two applications of stack?a) Stack is used to explain the processing of subroutine calls and their returns.b) Recursive procedures and evaluation of expressions can be implemented using

stack.

23. Define a suffix expression.

The notation used to write the operator at the end of the operands is called suffix notation.

Suffix _ operand operand operator

24. What do you meant by fully parenthesized expression? Give example.

Page 5

Page 6: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

A pair of parentheses has the same parenthetical level as that of the operator to which it corresponds. Such an expression is called fully parenthesized expression.

Ex: (a+((b *c) + (d * e))

25. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms?

Polish and Reverse Polish notations.

26. Convert the expression ((A + B) * C – (D – E) ^ (F + G)) to equivalent Prefix and Postfix notations.

Prefix Notation:^ - * +ABC - DE + FG

Postfix Notation:AB + C * DE - - FG + ^

27. What are the postfix and prefix forms of the expression?A+B*(C-D)/(P-R)

Postfix form: ABCD-*PR-/+Prefix form: +A/*B-CD-PR

28. Explain the usage of stack in recursive algorithm implementation?

In recursive algorithms, stack data structures is used to store the return address when a recursive call is Encountered and also to store the values of all the parameters essential to the current state of the procedure.

29. What is space complexity?The space complexity of an algorithm is the amount of memory it needs to run to completion.

30. What is time complexity?The time complexity of an algorithm is the amount of computer time it needs to run to completion.

31. Define Algorithm?Algorithm is a solution to a problem independent of programming

language. It consist of set of finite steps which, when carried out for a given set of inputs, produce the corresponding output and terminate in a finite time.

32. Define Program?Set of instructions to find the solution to a problem. It is expressed

in a programming language in an explicit and unambiguous manner.

33. What is divide and conquer method?

Page 6

Page 7: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

The basic idea is to divide the problem into several sub problems beyond which cannot be further subdivided. Then solve the sub problems efficiently and join then together to get the solution for the main problem.

34. What are the features of an efficient algorithm?Free of ambiguityEfficient in execution timeConcise and compactCompletenessDefinitenessFiniteness

Page 7

Page 8: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Part-B

1. Define Data structures and its classifications (5)Data Structure:

Data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

The possible ways in which the data items are logically related is defined by data structure.

It is the conceptual and concrete ways to organize data for efficient storage and efficient manipulation.

A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.

Data structure = Organized Data + Allowed Operation

Many algorithms require that we use a proper representation of data to achieve efficiency.

This representation and operations that are allowed for it are called data structures. Each data structure allows operations like insertion, access, deletion etc.

Classification of Data Structure

The Classification is based on how the data items are operated

Primitive / Non-Primitive Homogeneous / Heterogeneous Static / Dynamic Linear / Non-Linear

Primitive / Non-primitive:

Primitive data structures are basic data structure and are directly operated upon machine instructions, e.g., integer, character, strings

Non-primitive data structures are derived from primitive data structures, e.g., structure, union

Homogeneous/Heterogeneous

In homogeneous data structures all elements are of the same type.e.g., array

Page 8

Page 9: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

In heterogeneous data structures elements are of different types.e.g. structure.

Static/Dynamic

In static data structures memory is allocated at the time of compilation.

In dynamic data structures memory is allocated at run-time, through functions such

as malloc, calloc, etc.

Linear / Non-linear

Linear data structures maintain a linear relationship between their elements, e.g., array, stack, Queues

Non-linear data structures do not maintain any linear relationship between their elements, e.g. Tree and Graphs.

2. Explain in detail about arrays in c and its types with examples

Arrays

The very common linear structure is array. Since arrays are usually easy to traverse, search and sort, they are frequently used to store relatively permanent collections of data.

An array is a list of a finite number “n” of homogeneous data elements (i.e., data elements of the same type)

such that:a) The elements of the array are referenced respectively by an index

consisting of n consecutive numbers.b) The elements of the array are stored respectively in successive memory

locations.

For example, To create a collection of five integers, one way to do it, is to declare five integers

directly: int a, b, c, d, e

Suppose user need to find average of 100 numbers. No need to declare 100 variables.

int a, b, c, d, e, f, g, h, i, j, k, l, m, n... etc.,

An easier way is to declare an array of 100 integers:

int a[100];

Page 9

Page 10: ECE DS Notes 2010 New

6

A normal variable:

You place a value into “b” with the

statementb=6;

b

int b;

6

An Array variable:

int a[4];

a[0]

a[1]

a[2]

a[3]

You place a value into “a” with the statement like:

a[2]=6;array index

Data Structures and Algorithms SMVEC

General Syntax to declare an array

datatype array_name [size];

Subscript

Example: int a[5];

The five separate integers inside this array are accessed by an index. All arrays start at index zero and go to n-1 in C. Thus, int a[5]; contains five elements. For example:

a[0] = 12;a[1] = 9;a[2] = 14;a[3] = 5;a[4] = 1;

Operations of Array

Two basic operations in an array are storing and retrieving (extraction)

Storing: A value is stored in an element of the array with the statement of the form,

Data[i] = X

Page 10

Page 11: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

where I is the valid index in the arrayand X is the element

Extraction: The process of retrieving an element stored in an array.

X = Data [i] where i is the valid index of the array and X is the element.

Array Representation

The number n of elements is called the length or size of the array. If not explicitly stated, it will assume that the index starts from 0 and ends with n-1.

In general, the length (range) or the number of data elements of the array can be obtained from the index by the formula,

Length = UB – LB + 1where UB is the largest index, called the Upper Bound of an array LB is the smallest index, called Lower Bound of an array.

For Eg - If LB = 0 and UB = 4 then the length is,Length = 4 – 0 + 1 = 5

The elements of an array A may be denoted by the subscript notation (or) bracket notation,

A[0], A[1], A[2], … , A[N]

The number K in A[K] is called a subscript or an index and A[K] is called a subscripted variable.

Subscripts allow any element of A to be referenced by its relative position in A.

If each element in the array is referenced by a single subscript, it is called single dimensional array.

In other words, the number of subscripts gives the dimension of that array.

The array name will hold the address of the first element. It is called as BASE ADDRESS of that array. The base address can’t be modified during execution, because it is static. It means that the increment /decrement operation would not work on the base address.

Consider the first element is stored in the address of 1020. It will look like this,

1020 1022 1024 1026 102812 9 14 5 1

0 1 2 3 4.

a[0] means (a + 0) → 1020 + 0 → 1020 (locates the 1020) → referred element is 12

Page 11

a

Page 12: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

a[1] means (a + 1) → 1020 + (1 * size of datatype) → 1020 + 2 → 1022 → 9[int size is 2 byte]

a[2] means a + 2 → 1020 + 2 * size of datatype → 1020 + 4 → 1024

a[3] means a + 3 → 1020 + 3 * size of datatype → 1020 + 6 → 1026

a[4] means a + 4 → 1020 + 4 * size of datatype → 1020 + 8 → 1028

Array indexing helps to manipulate the index using a for loop. Because of that retrieval of element from an array is very easy.

For example, the following code initializes all of the values in the array to 0

int a[5]; /* Array Declaration */int i;

for(i=0;i<5;i++) /* Storing or Initializing array to 0 */ a[i]=0;

for(i=0;i<5;i++) /* Print array elements */ printf(“%d\n”, a[i]);

Advantages: Reduces memory access time, because all the elements are stored sequentially. By

incrementing the index, it is possible to access all the elements in an array. Reduces no. of variables in a program. Easy to use for the programmers.

Disadvantages: Wastage of memory space is possible. For example: Storing only 10 elements in a

100 size array. Here, remaining 90 elements space is waste because these spaces can’t be used by other programs till this program completes its execution.

Storing heterogeneous elements are not possible. Array bound checking is not available in ‘C’. So, manually we have to do that.

Program

#include <stdio.h>main(){ int a[5]; /* array declaration */ for(int i = 0;i<5;i++) { a[i]=i; }

Page 12

Page 13: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

for(int i = 0;i<5;i++) { printf("value in array %d\n",a[i]); }}

Two-dimensional Arrays

A two-dimensional mXn array A is a collection of m*n data elements such that each element is specified by a pair of integers (such as I, J), called subscripts, with the property that,

0 ≤ I m and 0 ≤ J n The element of A with first subscript i and second subscript j will be denoted by,

A[i,j] or A[i][j] (c language) Two-dimensional arrays are called matrices in mathematics and tables in business

applications; hence two-dimensional arrays are sometimes are called matrix arrays. There is a standard way of drawing a two-dimensional mXn array A where the

elements of A form a rectangular array with m rows and n columns and where the element A[i][j] appears in row i and column j.

A row is a horizontal list of elements, and a column is a vertical list of elements.

Example:Columns

0 1 2

0 A[0][0] A[0][1] A[0][2]

Rows 1 A[1][0] A[1][1] A[1][2]

2 A[2][0] A[2][1] A[2][2]

The two-dimensional array will be represented in memory by a block of m*n sequential memory locations.

Specifically, the programming languages will store the array either 1. Column by column, i.e. column-major order, or2. Row by row, i.e. row-major order.

3.Write C program for sorting the given numbers using single dimension array

#include<stdio.h>#include<conio.h>void main(){int a[10],t;int i,j,n;printf("Enter the limit of numbers:");scanf("%d",&n);printf("Enter %d Nos. ",n);for(i=0;i<n;i++)

Page 13

Page 14: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

scanf("%d",&a[i]);printf("\nThe sorted numbers are :\n");for(i=0;i<n;i++){ for (j=i+1;j<n;j++) if (a[i]>a[j])

{ t=a[i]; a[i]=a[j]; a[j]=t;

} printf("%d ",a[i]);

}getch();}

4.Write a C program to Multiplication two matrices of 3x3 orders.

#include<stdio.h>#include<conio.h> void main(){  int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;  printf("\nEnter the no. of rows and columns of first matrix");  scanf("%d %d",&m,&n);  printf("\nEnter the no. of rows and columns of second matrix");  scanf("%d %d",&o,&p);  if(n!=o){      printf("Matrix mutiplication is not possible");      printf("\nColumn of first matrix must be same as row of second matrix");  }  else{      printf("\nEnter the First matrix->");      for(i=0;i<m;i++){      for(j=0;j<n;j++)  {         scanf("%d",&a[i][j]);}}      printf("\nEnter the Second matrix->");    for(i=0;i<o;i++){      for(j=0;j<p;j++){           scanf("%d",&b[i][j]);}}

Page 14

Page 15: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

      printf("\nThe First matrix is\n");      for(i=0;i<m;i++){      printf("\n");      for(j=0;j<n;j++){           printf("%d\t",a[i][j]);      }      }      printf("\nThe Second matrix is\n");      for(i=0;i<o;i++){      printf("\n");      for(j=0;j<p;j++){           printf("%d\t",b[i][j]);      }              }      for(i=0;i<m;i++)      for(j=0;j<p;j++)           c[i][j]=0;      for(i=0;i<m;i++){      for(j=0;j<p;j++){           sum=0;           for(k=0;k<n;k++)               sum=sum+a[i][k]*b[k][j];           c[i][j]=sum;      }      }  }  printf("\nThe multiplication of two matrix is\n");  for(i=0;i<m;i++){      printf("\n");      for(j=0;j<p;j++){           printf("%d\t",c[i][j]);      }  } getch();}

5.Define Structure in C and its various types of structure declarationsDefinition

Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files

Page 15

Page 16: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Combined with pointers, can create linked lists, stacks, queues, and trees

A structure is a custom data type defined by the programmer. It can hold a collection of variables of different data types (unlike arrays, in which all the data elements are the same type).

The data items in a structure are usually related (different kinds of information about a person, or about a part, or about an account, etc.)

Each data item in a structure is called a member.

Sometimes these members are also called fields.

struct: Declares a structure, an object consisting of multiple data items that may be of different types.

3.2 DEFINING A STRUCTURE:

Syntax:struct tag{

data-type member 1;data-type member 2;…………data-type member m;

};

Here, struct is the required keyword; tag (optional) is a name that identifies structures of this type; and member1, meber2, …, member m are individual member declarations.

The individual members can be ordinary variables, pointers, arrays, or other structures.

A storage class cannot be assigned to an individual member, and individual members can not be initialized within a structure type declaration.

ARRAYS IN THE STRUCTURE:The derived data types like array can be included in the structure as a member.

Example:struct student{

int roll;char name[20];int marks[5];int total;float avg;char result[5];

}stu;

Page 16

optional

Page 17: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

NESTED STRUCTURES:

A structure variable may be defined as a member of another structure. In such situations, the declaration of the embedded structure must appear before the declaration of the outer structure.

Example:

struct date{

int day;int month;int year;

};struct bill{

int cno;char name[20];float amt;struct date billdate;struct date paydate;

}b1, b2;

POINTERS TO STRUCTURES:The address of a given structure variable can be obtained by using the & operator.

Pointers to structures, like all other pointer variables may be assigned addresses. The following statements illustrate this concept.

Example:struct student{

int regno;char name[20];char dept[10];int year;

};

6.Define and declare a structure for student record Struct student{

char name[50];int year;int m1,m2,m3,m4,m5;char result[50];

};

Void main(){

Struct student s={“RAM”,1980,65,45,95,35,25,265,”FAIL”};

Page 17

struct bill{

int cno;char name[20];float amt;struct date{

int day;int month;int year;

}billdate, paydate;

}b1, b2;

OR

Page 18: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

}

7.Define Stack and explain in detail the operations of Stack with pseudo codes A stack is an ordered collection of items where new items may be inserted or deleted

only at one end, called the top of the stack. A stack is a data structure that keeps objects in Last- In-First-Out (LIFO) order, Objects are added to the top of the stack Only the top of the stack can be accessed.

Stacks have some useful terminology associated with them:

Push To add an element to the stack Pop To remove an element from the stock Peek To look at elements in the stack without removing them LIFO Refers to the last in, first out behavior of the stack FILO Equivalent to LIFO

stack (data structure)

Operations of stack is

1. PUSH operations 2. POP operations 3. PEEK operations

The Stack ADT

A stack S is an abstract data type (ADT) supporting the following three methods:push(n) : Inserts the item n at the top of stack

pop() : Removes the top element from the stack and returns that top element. An error occurs if the stack is empty.

peek(): Returns the top element and an error occurs if the stack is empty.

1. Adding an element into a stack (called PUSH operation)

Page 18

Page 19: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Adding element into the TOP of the stack is called PUSH operation.

Check conditions :

TOP = N , then STACK FULL

where N is maximum size of the stack.

Adding into stack ( PUSH algorithm )

procedure add(item : items); {add item to the global stack stack ; top is the current top of stack and n is its maximum size} begin     if top = n then stackfull;     top := top+1;     stack(top) := item; end: {of add}

. Deleting an element from a stack. (Called POP operation)

Deleting or Removing element from the TOP of the stack is called POP operations.

Check Condition:

TOP = 0, then STACK EMPTY

Deletion in stack ( POP Operation )

procedure delete(var item : items); {remove top element from the stack stack and put it in the item} begin     if top = 0 then stackempty;     item := stack(top);     top := top-1; end; {of delete}

Peek Operation:

Returns the item at the top of the stack but does not delete it. This can also result in underflow if the stack is empty.

Page 19

PEEK

6item /

element

operation

48

top

Stack

6

48

top

Stack

6

Page 20: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Algorithm:

PEEK(STACK, TOP)BEGIN

/* Check, Stack is empty? */if (TOP == -1) then

print “Underflow” and return 0.else

item = STACK[TOP] / * stores the top element into a local variable */

return item / * returns the top element to the user */end

8.Write a C Code to implement the operations of stack using array data structure #include<stdio.h> #include<conio.h>#include<stdlib.h>#define size 5int s[size],top,i,item,choice;

//Push Operationvoid push(int item){

top++; s[top]=item;

}

//Pop Operationint pop(){

item=s[top]; top--; printf("The popped element is %d \n",item); return(item);

}

// Peek Functionvoid peek(){

printf(" The value of the top is =%d",s[top]);}

Page 20

Page 21: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

//Display the Stack Contentvoid display(){

if (top==-1) printf("\nStack Underflow - No Elements\n"); else { printf("\nStack Content:");

for(i=top;i>=0;i--) printf("\n%d",s[i]);

}}

void main(){

top=-1; clrscr(); printf("\n\tImplementation of Stack using Array\n"); printf("\n\t~~~~~~~~~~~~ ~~ ~~~~ ~~~~ ~~~~~ \n");

do { printf("\nStack Operations"); printf("\n------- -------------");

printf("\n\t1.Push Element\n\t2.Pop Element\n\t3.Peek Element\n\t4.Stack Content\n\t5.Exit");

printf("\nChoice : "); scanf("%d",&choice);

switch(choice) {

case 1: if(top==size-1)

printf("Stack Overflow - Not Possible to Push\n");else printf("\nEnter the item to push : "); scanf("%d",&item); push(item);break;

case 2: if(top==-1) printf("\nStack Underflow - No Elements\n"); else item=pop(); break;

Page 21

Page 22: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

case 3: peek(); break;

case 4: display();

break; case 5:

printf("\n"); for(i=1;i<=79;i++) printf("~"); break;

default: printf("\nInvalid option\n");

} }while(choice!=5);

}

9.List down the different types of expression representation and give examples. (5) Infix: An expression having an operator in between two operand , eg (a+b) , (6+3)Postfix:

An expression when an operator follows the two operands eg: ab+ ,63+Note: this expression does not have paranthesis. This is the characterization of

postfix expressionPrefix:

An expression where the operator precede the two operands eg:+abNote: this expression doesn t have paranthesis

Infix Prefix Postfix

a + b + a b a b +

a + b * c + a * b c a b c * +

(a + b) * (c - d) * + a b - c d a b + c d - *

b * b - 4 * a * c    

40 - 3 * 5 + 1    

10.Discuss the algorithm in detail to convert the given infix expression to postfix expression

Page 22

Page 23: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Algorithm:

Step 1: Initialize the stack.Step 2: While (INSTR!=NULL)Step 3: ch=get the char from INSTRStep 4: if (ch==’(’ ) then Push ch the stack. else if (ch==’)’) then Pop the data from the stack and append the data into POSTSTR. Until ‘(‘ is read from the stack. else while (precedence(top)>=precedence(ch)) Pop data and append to POSTSTR.Step 5: Push ch into the stack.Step 6: Pop all the elements stack and append POSTSTR until the stack is empty.Example:Consider the equation, a+b*cIts postfix expression is, abc*+It is obtained by the following stepsSymbol Stack Postfixa + A+ + Ab + Ab* +* Abc +* Abc

abc*+ Thus the Postfix Expression is obtained.

11.Write and explain the procedure to evaluate the postfix expression Algorithm: Opnd stack=empty stack /* scan the input stack*/

While(not end of input){Symb=next input characterIf(symb in an operand)Push(opnd stack, symb);Else{/*symbol in operator*/Opd 2=pop(opnd stack)Opd1=pop(opnd stack)Result/value=apply operator to two operandsPush(opnd stack,value);}/* end stack*/}

Page 23

Page 24: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Return(pop(opnd stack));

Eg:Infix expression:6+(3-2)*5=?Postfixexpression: 632-5*+

symbol Opnd 2 Opnd 1 Result stack

6 - - - 6

3 - - - 6,3

2 - - - 6,3,2

- 2 3 1 6,1

5 - - - 6,1,5

* 5 1 5 6,5

+ 5 6 11 11

Page 24

Page 25: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Unit-2Part-A

1. Define Recursion Recursion is averypowerful programming tool. It is aprocess of doing the same task again and again for some specific .Eg: Fibonacci,factorial,multiplication of natural number.

2. List the efficiency of Recursion In general a non recursive version of a program will execute more

efficiency in terms of line complexcity than recursive version Recursive version the compiler is unable to identify the least

important variables and unneccessarly they get stacked

3. Give the recursion procedure for factorial calculationIf(n==0)

Fact=1;Else{

X=n-1;Y=x!;Fact=n*y;

}

4. Explain the usage of stack in recursive algorithm implementation?

In recursive algorithms, stack data structures is used to store the return address when a recursive call is Encountered and also to store the values of all the parameters essential to the current state of the procedure.

5. What is recursive algorithm?An algorithm is said to be recursive if the same algorithm is invoked in thebody. An algorithm that calls itself is Direct recursive. Algorithm A is said to beindeed recursive if it calls another algorithm, which in turn calls A.

5. Define Queue It is the ordered collection of items from which item can be inserted in one end rear end, item can be removed from oher end called front end

6. Define Queue and its types It is the ordered collection of items from which item can be inserted in one end rear end, item can be removed from oher end called front end

Page 25

Page 26: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Types of queue:Circular queue

Priority queuelinear queue

7. Write down the operations that can be done with queue data structure?

Queue is a first - in -first out list. The operations that can be done with queue are addition and deletion.

8. Define Circular QueueThe queue, which wraps around upon reaching the end of the array is

called as circular queue.

9. How do you test for an empty Queue?The condition for testing an empty Queue is front= rear.

10. Define DQueueDouble entered Queue. It is a linear list in which insertions and

deletion are made or from either end of the structure.

Page 26

Page 27: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

11. Define priority queue.A Queue in which we are able to insert items or remove items from any position based on some priority is after referred to as a priority Queue

12. Short note on priority queue?Sometimes the user programs that are waiting to be processed

from a waiting queue. This queue may not operate on a strictly first out basis, but on some complex priority scheme based on such factors as what compiler is being used the execution time required the number of print lines desired etc. the resulting queue is sometimes called a priority queue.

13. Define Circular Queue.Another representation of a queue, which prevents an excessive use

of memory is to arrange elements Q[1], Q[2],…..Q[n] in a circular fashion.

14. Minimum number of queues needed to implement the priority queue?Two, One queue is used for actual storing of data and another for

storing priorities

15. Write down the operations that can be done with queue data structure?

Queue is a first - in -first out list. The operations that can be done with queue are addition and deletion.

16. What is a circular queue?The queue, which wraps around upon reaching the end of the array

is called as circular queue.

18. Define NodeAn element or node consists of two fields namely an information field

called INFO and a pointer field called LINK. The name of the element is denoted by node.

17. What are the different ways to implement list?Simple array implementation of listLinked list implementation of list

Page 27

Page 28: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

11. What is meant by list ADT?List ADT is a sequential storage structure. General list of the form

a1, a2, a3.…., an and the size of the list is 'n'. Any element in the list at the position I is defined to be ai, ai+1 the successor of ai and ai-1 is the predecessor of ai.

12. What is a linked list?Linked list is a kind of series of data structures, which are not

necessarily adjacent in memory. Each structure contain the element and a pointer to a record containing its successor.

13. What is a doubly linked list?In a simple linked list, there will be one pointer named as 'NEXT

POINTER' to point the next element, where as in a doubly linked list, there will be two pointers one to point the next element and the other to point the previous element location.

14. Define double circularly linked list?In a doubly linked list, if the last node or pointer of the list, point to

the first element of the list, then it is a circularly linked list.

15. What is the need for the header?Header of the linked list is the first element in the list and it stores

the number of elements in the list. It points to the first data element of the list.

Define circular list and mention its disadvantages?Last node points to first node is called circular list.a. disadvantage in using circular list.b. It is possible to get into an infinite loop.c. We are able to detect the end of the list.

What are the applications of link list?• The linear link list is used for the polynomial manipulation such as addition,subtraction, multiplication and division.• Describe the organization for maintain a dictionary of names.

List three examples that uses linked list?Polynomial ADTRadix sortMulti lists

Page 28

Page 29: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Part-B

1. Explain how recursion is implemented using stacks?

Recursion is the name given to the technique of defining a set or a process in terms of itself.

The factorial function is FACTORIAL(N) = 1, if N = 0N * FACTORIAL (N-1), otherwise

The facility available to implement recursion by the programmer is the procedure (function in subroutine). Procedures in programming languages are a convenience to the programmer since they enable him to express just once an algorithm, which is required in many places in a program.

Recursive ProcedureA Procedure that contains a procedure call to itself or a procedure

call to a second procedure, which eventually causes the first procedure to be called, is known as a recursive procedure.

Two types of recursion1. Recursively defined functions. Ex. Factorial2. Recursive use of a procedure Ex: Ackermann’s function.

The four parts of iterative process:• Initialization – parameters of fix are set to their initial values.• Decision – determine whether to remain in the loop• Computation.• Update – The decision parameter is updated to transfer to the next interaction result.

General algorithm for recursive procedure1. Save the parameters, local variables and return address2. If the base criterion has been reached, then perform the final computation and go to step 3; otherwise, perform the partial computation and go to step 1.3. Restart the most recently saved parameters, local variables, and return address, go to this return address

Algorithm FACTORIAL

1. CALL PUSH(A,TOP,TEMP_REC)2. IF N = 0 Then FACTORIAL 1

Go to step 4 Else PARM <- N – 1

ADDRESS <- step 3

Page 29

Page 30: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Go to step 13. FACTORIAL N * FACTORIAL4. TEMP_REC <- POP(A,TOP)

GOT TO ADDRESS

2. Write Code for Fibonacci Series Generation upto n terms using recursion

#include<stdio.h>#include<conio.h>#include<stdlib.h>

void main(){ int n; int x=-1,y=1; void fibo(int,int,int); clrscr(); printf("\t\t\FIBONACCI SERIES USING RECURSION"); printf("\nENTER THE NUMBER:"); scanf("%d",&n); printf("\nFIBONACCI SERIES IS\n"); fibo(n,x,y); getch();}

void fibo(int n1,int a,int b){ int c; if(n1<=0) { exit(0); } else { c=a+b; printf("\n%d",c); a=b; b=c; } fibo(n1-1,a,b)}

3. Write a C Code to implement the factorial calculation using recursion

Page 30

Page 31: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

#include<stdio.h>#include<conio.h>

void main(){

int n; long int fact(int); clrscr(); printf("\n\t Factorial Calculation"); printf("\n\t ----------- --------------"); printf("\n\nEnter the Value : "); scanf("%d",&n); printf("\n\nFactorial of %d is :%d ",n,fact(n)); getch();

}

//Factorial Functionlong int fact(int n){

if(n==0||n==1)return 1;

elsereturn(n*fact(n-1));

}

Page 31

Page 32: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

4. Write notes on queues and its types?Queues

A sub class of lists permits deletion to be performed at one end of list and insertion at the other.

The information in such a list is processed in the same order as it was recorded, that is on a first-in, first-out (F1F0) or a first come, first-served (FCFS) basis. This type of list is frequently referred to as a queue.

Eg:- Time sharing computer system where many users share the system simultaneously.

The queue that may not operate on a strictly FIFO basis but on complex priority scheme, the resulting queue is sometimes called priority queue.

Procedure QINSERT(Q,F,R,N,Y)

The procedure inserts Y at the rear of the queueF,R – pointer to front and rearQ – Consisting of N elementsY – Element inserted on queue.1. IF R _ NThen Write(‘OVERFLOW’)Return2. R R + 13. Q[R] Y4. If F = 0Then F 1Return

Function QDELETE (Q, F, R)The function deletes and returns the last elements of the queue.1. IF F = 0Then Write (‘UNDERFLOW’)Return (0) (0 denotes as empty queue)2. Y <- Q[F]3. If F = RThen F R 0Else F F + 1 (increment front pointer)4. Return (Y)

Page 32

Page 33: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Queue Types

Circular QueueAnother representation of a queue, which prevents an excessive use of memory is toarrange elements Q[1], Q[2],…..Q[n] in a circular fashion.

DequeueA dequeue is a linear list in which insertions and deletions are made to or from either end of the structure.

Page 33

Page 34: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

5. Write notes on queues and its types?Queues

A sub class of lists permits deletion to be performed at one end of list and insertion at the other.

The information in such a list is processed in the same order as it was recorded, that is on a first-in, first-out (F1F0) or a first come, first-served (FCFS) basis. This type of list is frequently referred to as a queue.

3. Write about Operations in linked linear lists.

Operations on Linear List Using Singly Linked storage structures

Function to insert X.

Function INSERT ( X, FIRST)1. If AVAIL = NULLThen Write (‘ AVAILABILITY STACK UNDERFLOW’)Return (FIRST)2. NEW AVAIL3. AVAIL LINK(AVAIL)INFO(NEW) XLINK(NEW) FIRST5. Return (NEW)Function to insert X at the end of the listFunction INSEND(X, FRIST)1. If AVAIL = NULLThen Write (‘ AVAILABILITY STACK UNDERFLOW’)Return (FIRST)2. NEW AVAIL3. AVAIL LINK(AVAIL)4. INFO(NEW) XLINK(NEW) NULL5. If FIRST = NULLThen Return (NEW)6. SAVE FIRST7. Repeat while LINK(SAVE) _ NULL8. LINK(SAVE) NEW9. Return(FIRST)General Algorithm for inserting a node into an ordered linear list1. Remove a node from the availability stack.2. Set the fields of the new node.3. If the linked list is empty then return the address of the new node.4. If the node precedes all others in the list then insert the node at the end of the listand return its address.5. Repeat them step 6 with information contain to the node in the list is less than theinformation contents of the new node.6. Obtain the next node in the linked list.

Page 34

Page 35: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

7. Insert the new node in the list and the return address of its first node.Function INSORD(X, FIRST)X is to be inserted so that it preserves the ordering of the terms in increasing order1. If AVAIL = NULLThen Write(‘AVAILABILITY STACK UNDERFLOW’)Return(FIRST)2. NEW AVAIL3. AVAIL LINK(AVAIL)4. INFO(NEW) X5. If FIRST = NULLThen LINK(NEW) FIRSTReturn(NEW)6. If INFO(NEW) _ INFO(FIRST)Then LINK(NEW) FIRSTReturn (NEW)7. SAVE FIRST8. Repeat while LINK(SAVE) _ NULL and INFO(LINK(SAVE)) _ INFO(NEW)SAVE LINK(SAVE)9. LINK(NEW) LINK(SAVE)LINK(SAVE) NEW

11. Return (FIRST)

A general algorithm for deleting node from a linked list1. If the linked list is empty then write underflow and return2. Repeat step 3 while the end of the list has not been reached and the node has not beenfound.3. Obtain the next node is in the list and records its predecessor node.4. If the end of the list has been reached then write node not found and return.a) Delete the node form the list.b) Return the node to availability area.Procedure DELETE(X, FRIST)This procedure deletes the node whose address is given by X.1. if FIRST = NULLthen Write(‘UNDERFLOW’)Return2. TEMP FIRST3. Repeat thru step 5 while TEMP ¹ X and LINK(TEMP) ¹ NULL4. PRED TEMP5. TEMP LINK(TEMP)6. If TEMP ¹ XThen write (‘NODE NOT FOUND’)Return.7. If X = FIRSTthen FIRST LINK(FIRST)else LINK(PRED) LINK(X)

Page 35

Page 36: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

8. LINK(X) AVAILAVAIL XReturn.CopyGeneral algorithm to copy a linked list1. If the list is empty return null.2. If the availability stack is emptythen write availability stack underflow and returnelse copy the first node.3. Repeat thru step 5 while the end of the old list has not been reached.4. Obtain next node in the old list and record its predecessor node.5. If the availability stack is empty then write availability stack underflow and return elsecopy the node and add it to the rear of the new list.6. Set link of the last node in the new list to null and return.Function COPY(FIRST)This function makes a copy of the list.1. if FIRST = NULLthen Return(NULL)2. If AVAIL = NULLThen Write(‘AVAILABILITY STACK UNDERFLOW’)Return(0)Else NEW AVAILAVAIL LINK(AVAIL)FIELD(NEW) INFO(FIRST)BEGIN NEW3. SAVE FIRST4. Repeat thru step 6 while LINK(SAVE) ¹ NULL5. PRED NEWSAVE LINK (SAVE)6. If AVAIL = NULLThen Write(‘AVAILABILITY STACK UNDERFLOW’)Return(0)Else NEW AVAILAVAIL LINK(AVAIL)FIELD(NEW) INFO(SAVE)PTR(PRED) NEW7. PTR(NEW) NULLReturn (BEGIN)

7. Explain doubly linked linear lists?Doubly Linked Linear ListIn certain applications the links are used to denote the predecessor and successor of anode. The link denoting the predecessor of a node is called the left link and that denoting its

Page 36

Page 37: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

successor is right link. A list containing this type of node is called a doubly linked linear list or atwo-way chain.InsertionGeneral algorithm for inserting a node to the left of a given node in a doubly linked list1. Obtain a new node and set its fields.2. If the list is emptyThen insert the node in the listUpdate left and right pointers to the list and return.3. If the node is to be inserted at the front of the list then insert the nodeUpdate the left pointer to the list and return.4. Insert the node in the middle of the list and return.Procedure DOUBINS (I,R,M,X)The insertion is to be performed to the left of a specified node with its address given bythe pointer variable M. The information is in X.1. NEW NODE2. INFOR(NEW) X3. If R = NULLThen LPTR(NEW) RPTR(NEW) NULLL R NEWReturn4. If M = LThen LPTR(NEW) NULLRPTR(NEW) MLPTR(M) NEWL NEWReturn5. LPTR(NEW) LPTR(M)RPTR(NEW) MLPTR(M) NEWRPTR(LPTR(NEW)) NEWReturnDeletionPossibilities in deletion1. If the list contains a single node, then deletion results in an empty list with the leftand right most pointers set the NULL.

If the node being deleted could be the left most node of the list. In this case thepointer variable L must be changed.General Algorithm:1. If the list is empty then write underflow and return.2. If a single node exist in the listThen set the left and right pointers of the list to nullElse if the left most node in the list is being deleted

Page 37

Page 38: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Then delete the node and update the left pointer to the listElse if the rightmost node in the list is being deletedThen delete the node and update the right pointers to the listElse delete the node from the middle of the list.3. Restore the deleted node to the availability node and returnProcedure DOUBDEL (L, R, OLD)To delete the node whose address is contained in the variable OLD1. If R = NULLThen Write (‘UNDER FLOW’)Return2. if L = Rthen L R NULLelse if OLD = Lthen L RPTR(L)LPTR(L) NULLElse if OLD = Rthen R LPTR(R)RPTR(R) NULLElse RPTR(LPTR(OLD)) RPTR(OLD)LPTR(RPTR(OLD) ) LPTR(OLD)3. Restore (OLD)Return

Explain the linked list implementation of stack ADT in detail?_ Definition for stack_ Stack model_ Figure_ Pointer-Top_ Operations• Coding• Example figure5. Explain the array implementation of queue ADT in detail?_ Definition for stack_ Stack model_ Figure_ Pointer-FRONT, REAR_ Operations

Page 38

Page 39: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Unit-3

Part-A

1. Define tree?A tree is a data structure, which represents hierarchical

relationship between individual data items.

2. Define leaf?In a directed tree any node which has out degree o is called a

terminal node or a leaf.

3. What is meant by directed tree?Directed tree is an acyclic diagraph which has one node called its

root with indegree o whille all other nodes have indegree I.

4. What is a ordered tree?In a directed tree if the ordering of the nodes at each level is

prescribed then such a tree is called ordered tree.

5. What are the applications of binary tree?Binary tree is used in data processing.

a. File index schemesb. Hierarchical database management system

10. What are the two methods of binary tree implementation?Two methods to implement a binary tree are,

a. Linear representation.b. Linked representation

11. What is meant by traversing?Traversing a tree means processing it in such a way, that each

node is visited only once.

12. What are the different types of traversing?The different types of traversing are

a. Pre-order traversal-yields prefix from of expression.b. In-order traversal-yields infix form of expression.c. Post-order traversal-yields postfix from of expression.

13. Define pre-order traversal?Pre-order traversal entails the following steps;

a. Process the root nodeb. Process the left subtreec. Process the right subtree

14.Define post-order traversal?

Page 39

Page 40: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Post order traversal entails the following steps;a. Process the left subtreeb. Process the right subtreec. Process the root node

15. Define in -order traversal?In-order traversal entails the following steps;

a. Process the left subtreeb. Process the root nodec. Process the right subtree

16. What is a balance factor in AVL trees?Balance factor of a node is defined to be the difference between

the height of the node's left subtree and the height of the node's right subtree.

17. What is meant by pivot node?The node to be inserted travel down the appropriate branch track

along the way of the deepest level node on the branch that has a balance factor of +1 or -1 is called pivot node.

18. What is the length of the path in a tree?The length of the path is the number of edges on the path. In a

tree there is exactly one path form the root to each node.

19. Define expression trees?The leaves of an expression tree are operands such as constants or

variable names and the other nodes contain operators.

Page 40

Page 41: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Part-B

TREE:-Tree is a non linear data structure.A tree is a finite set of one or more nodes such that

1. There is a specially designated node called “Root”.2. The remaining nodes are partitioned into sub tree of the tree.

TREE TERMINOLOGY:-

ROOT: A unique node to which all sub trees are attached is called as root of a tree.

Degree of a node: It is termed as number of subtrees of the node.

Leaf or terminal nodes: The nodes which are having degree zero is called as leaf or terminal nodes.

Internal nodes: The nodes other than the root and the leaves are known as internal nodes.

Parent nodes: A node which is having further sub branches are called as parent node of that sub tree. From e.g.: B&C are parent nodes

Predecessor: The node that occurs previous to some other nodes is called as predecessor.

Successor: The node that occurs next to some other nodes is called as successor.

Level of a tree: Root node will be at level 0. Its children will be at level 1. Grand children will be at level 2 and so on.

Height of the tree: The maximum level of a tree is called maximum height of the tree.

Page 41

A

C

F

B

ED

Page 42: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Siblings: The nodes having the same parents or nodes at the same level are called as siblings.

Binary tree: A binary tree is a finite set of node which is either empty or consists of a root and two disjoint binary tree is called as left binary tree & right binary tree.

Page 42

A

B C

DE F

G

Page 43: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Complete binary tree: A complete binary tree is a binary tree structure where all the leaf nodes are available in the same level.

Root-1Degree of 1- 2.Degree of 2- 2.Degree of 3- 2.Levels are 4,5,6,7.Internal node-2,3.Parent node-2,3.Level-1-0. 2,3-1. 4, 5, 6, 7-2.Sibilings:4,5,6,7,2,3.Height:2

Page 43

1100000000000

2 3

4 5 6 7

Page 44: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Representation of a binary tree:

There are two ways of representing a binary tree. -linked representation -sequential representation

Linked representation:

In binary tree, each node has :1) Left child,2) Right child,3) Data piece.

- The left child is the left link which points left sub tree of a node. - the right child is the right link which points the right sub tree of a node.

Advantages:1) No wastage of memory.2) No depth is required3) Insertion and deletion are easy to process.4) No need to adjust the list.

Disadvantages:1) No direct access of nodes2) Additional memory is required.

C structure: Struct node{ int data; Struct node*left child; Struct node*right child;

Page 44

L Data R

12

5 13

6 7

12

5 13

6 7

Page 45: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

}

Sequential representation:

0 1 2 3 4

0 1 2 3 4 5 6

Applications of binary tree: Binary tree traversals: Binary tree traversals mean visiting the nodes in a tree exactly once. There are three types of traversals namely -In order traversal, -Preorder traversal, -Post order traversal.

Inorder or symmetric order traversal: To traverse a non empty binary tree in in order fashion, then

1) Traverse the left sub tree in in order2) Visit the root3) Traverse the right sub tree in in order.

E.g.:

BAC DBEAC 421536

Page 45

a b c d e

A B C D E

a

b c

de

a

b c

ed

AA1

B C

D E

3CB 2

4

5 6

Page 46: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Preorder traversal: To traverse a non empty binary tree in pre order fashion, then

1) Traverse the root.2) Traverse the left sub tree in preorder.3) Traverse the right sub tree in pre order.

E.g.:

ABC ABDEC 124356

Postorder traversal:

To traverse a non empty binary tree in post order fashion, then1) Traverse the right sub tree in post order.2) Traverse the left sub tree in pre order.3) Visit the root.

B

-BCA DEBCA 425631

In order Pre order Post orderVoid ignored (node*root) Void pre order (node*root) Void post order (node*root) { { { if (root! =NULL) if (root! =NULL) if (root! =NULL){ { {In order(root->left); printf(root->data); Post order(root->left);Printf (root->data); preorder (root->left); Post order (root->right);In order(root->right); preorder(root->right); Printf(root->data);

Page 46

A

CB

A

BC

D EE

1

2

4

3

5

6

A

B C

A

B C

D E

1

23

4

5 6

Page 47: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Binary search tree: Nodes are arranged in a systematic manner, means values at the left sub tree are less than the root node value and the remaining nodes values less than the root node value are arranged on the right hand side.Left child values < Root node < Right child values.

Procedure to construct a Binary search tree:1. Place the first element as root.2. When placing the element at the next level,

a. Compare the value of ‘in’ element in the root.b. If the value of ‘in’ element is smaller place it on the left sub tree.c. Otherwise place it on the right side. Eg. 78,24,65,41,51,26,81,100,88.

Page 47

10 101010110101100

7 1521111111

15

9

12

18

5

787

24

81 65

41

26

51

100

88

Page 48: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Constructing binary tree for Arithmetic expressions: Arithmetic expressions can also be constructed using binary tree. Processing of arithmetic expressions starts from the last level and go up to the root, where the result is obtained. E.g.: B*C

Operator must be the parent node and operands are child nodes.Eg: A= B*C

Threaded Binary Tree: In a Binary tree, the left and the right child pointers of all the leaf nodes are said to be NULL, while traversing the tree.Replacing all the NULL pointers of the leaf nodes with pointers to successor in that traversals. These pointers are called as Threads and such a tree is called as Threaded binary tree. Setting of threads to the leaf nodes to link to its predecessor or successor nodes.

>

Page 48

* +++6555

C

=

A *

C

B

A

B C

B

Page 49: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Two types:

Right in Threaded Binary tree and Left in threaded binary tree.

RITBT: If right child pointers nodes with empty right sub tree, then may be node to point its successor.

LITBT: If left child pointers nodes with empty left sub tree, then may be node to point its predecessor.

Head

Page 49

A B D

C E F

G

Page 50: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

HUFFMAN’s ALGORITHM Developed by david Huffman. It is a entropy encoding algorithm. Used for lossless data compression. Uses variable length codes for encoding a source. Variable codes are derived based on the frequency of occurrences of the symbol. Consider the alphabet of “N” symbols and non message consisting of symbols. To encode the long message assigning a bit string code of each symbol and concatenating the individual code of the symbols. Eg; assume ABCD are the symbols and the codes assigned to all the symbols are, Symbol codesA 010B 100C 000D 111

Given message is ABACCBA is encoded as 010100010000000111010.It requires 21 bits to encode the message.Suppose if 2 bits are assigned to the symbols then, Symbol codesA 00B 01C 10D 11

Now ABACCDA is encoded as 00010010101100This requires 14 bits to be encoded. Thus the length of the message is minimised.The procedure of Huffman is to find the minimised code length to encode a message.The procedure assigns variable length codes which is instead of fixed length code to symbols based on the frequency of occurrences of symbols.In the given message ABACCDA, the symbols B and D appears only once whereas A appears 3 tomesIf a code is chosen so that the letter A is assigned shorter bit string than the letter of symbols B and D.then the length of encoded message will be small. Symbol codesA 0B 110C 10D 111

ENCODING SCHEME: Symbol codesA 3B 1C 2D 1

1. Find the two symbols that appear least times i.e. B and D.

Page 50

Page 51: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

2. The least bit of their codes differentiate one from other,

0 is assigned for B 1 is assigned for D.

3. combine these two symbols as BD and sum the frequencies of these symbols A->3

C->2 BD->2 4.similarly the least frequencies are added,

(a)0 is for C 1 is for BD (b)0 is for A and 1 is for CBD

5. thus we get ABCD->7.DECODING; Scan the big screen from left to right. If 0 is encountered as first bit, the symbolos is A, else CBD and next bit is examined.If the second bit is 0, the symbol is C else the symbol is BD and the next bit is examined.If the third bit is 0, the symbol is B else the symbol is D.By combining two symbols A and CBD, the new symbol ACBD is generated.the codes for the above symbols are assigned as,A->0,CBD->1If zero is encountered in the encrypted message , the encoded symbol is A.If i is encountered in the encrypted message then the encoded symbol is CBD. Similarly the symbol CBD is generated by combining C abd BD respectively The codes are C=10,BD=11Two bits are used to code the symbols. In that the first bit indicates the symbol is one of the symbols of C,B,D and the second bit indicates either C or BD.Similarly B and D are coded as B->110, D->111 Symbols that appear in less freq in message are assigned shorter codes than the symbols that appear infrequently. HUFFMANN TREE;

Binary tree is used to represent the process of combining two symbols. Each node of tree represents a symbol and each leaf represents a symbol assigned to an alphabet.CODED TREE; Once the Huffman tree is constructed the code of any symbol in alphabet can be generated.

The codes are generated by starting at the leaf that represents the symbol and climbing upto the root.

The code is initialised to NULL. Each time that a left branch is climbed ‘0’ isappende to beginning of the code.

Each time when a branch is climbed,1 is appended to beginning of code.From the above Huffman tree the codes are generated as starting from leaf and

climbing up to the root SYMBOL CODESA 0B 110C 10D 111 ALGORITHM:

Page 51

Page 52: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

INPUTS; For n number of symbols in the original alphabet.Frequency[i]-it states frfequency of symbols -array of size n.

-i denotes the i symbolCode[i]- denotes the code of the symbol.Position[i]-use to identify a point in the tree from which it starts its constructing code for a symbol in the alphabetIsleft-> denotes the operations determines either zero or one to be placed in front of code when climbing the tree.Info->the frequency of occurrence of the symbols.Rootnodes-> points the root of a partial binary tree.Pqinsert->it is an operation which inserts a pointer into the priority queue.Pqmindelete->an operation which removes the pointer to the node with “info” value from priority queue

Game Trees :Game tree is an application of trees for tic-tac-toe game.

- Game trees are used to determine the best move in tic-tac-toe game from the given board position.

- By using the game trees, the best next move can be determined by considering all possible moves and resulting positions.

- The move selected should be the one that results in the board position with highest value.

Evaluation Function :

The evaluation is a function that accepts a board position and indication of a player (x or o) and returns a numerical value that represents the position for the next player.

- The largest value returned by the function is the better position.

- The winning position yields the largest possible value and the losing position yields the smallest value.

- Applying static evaluation function to a board position ,the value of the winner can be calculated.

- This process is called minimax method.

Evaluation Condition :

The no.of rows, columns, diagonals remaining possible to move for 1 player minus the no.of places remaining open for the opponent.

Page 52

Page 53: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

- This evaluation condition is static and evaluates a static board position.

- So it can only look for the current board position.

- It does not look ahead for the possible conditions.

Disadvantages of static evaluation function :

i) It does not good enough to predict the outcome of the game.ii) Most games are too complex for static evaluations to determine

the best response.

Look ahead level :Look ahead level of a game tree defines the future move of the players.- Starting at any position, it is possible to construct a tree of possible

board positions that may result for next move.

Minimax Algorithm :Minimax algorithm uses static evaluation function which gives the best

move for a current board position.

Minimax (Player,Board)If (game over in current board position)return winner of the game.Children = all legal moves for player from current board position.If (maxturn) return maximum score of calling minimax on all the children.Else (ministurn) return minimum score of calling minimax on all the children.

Working principle of game trees :

1. Assign + symbol for the player who must move at the root position.2. Assign – symbol for the opponent.3. Find the best move for + from the roots game position.4. The remaining nodes of the tree should be assigned with +node or –

node depending upon which player must move the next position.5. If the game position of all the children of a +

Page 53

Page 54: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

The + should consider the move which yields the maximum value.So the value of the +node should be maximum of its children.

6. After the + node has moved, the – node will select the move that yield minimum evaluation from the children.

7. To decide the best move for player =,the children of + should be evaluated using a static evaluation function.

Unit-4

Page 54

Page 55: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Sorting

1. What is meant by sorting?Ordering the data in an increasing or decreasing fashion according

to some relationship among the data item is called sorting.

2. What are the two main classifications of sorting based on the source of data?

a. Internal sorting b. External sorting

3. What is meant by external sorting?External sorting is a process of sorting in which large blocks of data

stored in storage devices are moved to the main memory and then sorted.

4. What is meant by internal sorting?Internal sorting is a process of sorting the data in the main

memory.

5. What are the various factors to be considered in deciding a sorting algorithm?

a. Programming timeb. Execution time of the programc. Memory needed for program environment

6. What is the main idea behind insertion sort?The main idea of insertion sort is to insert in the ith pass the ith

element in A (1) A (2)...A (i) in its rightful place.

7. What is the main idea behind insertion sort?The main idea behind the selection sort is to find the smallest

element among in A (I) A (J+1)...A (n) and then interchange it with a (J). This process is then repeated for each value of J.

8. What is the basic of shell sort?Instead of sorting the entire array at once, it is first divide the array

into smaller segments, which are then separately sorted using the insertion sort.

9. What is the other name for shell sort?Diminishing increment sort.

10. What is the purpose of quick sort?The purpose of the quick sort is to move a data item in the correct

direction, just enough for to reach its final place in the array.

Page 55

Page 56: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

11. What is the advantage of quick sort?Quick sort reduces unnecessary swaps and moves an item to a

greater distance, in one move.

12. What is the average efficiency of heap sort?The average efficiency of heap sort is 0 (n(log2 n)) where, n is the

number of elements sorted.

13. Define segment?When large blocks of data are to be sorted, only a portion of the

block or file is loaded in the main memory of the computer since, it cannot hold the entire block. This small portion of file is called a segment.

14. Name some of the external sorting methods?a. Polyphase mergingb. Oscillation sortingc. Merge sorting

15. When is a sorting method said to be stable?A sorting method is said to be stable, it two data items of matching

values are guaranteed to be not rearranged with respect to each other as the algorithm progresses.

16. Name some simple algorithms used in external sorting?a. Multiway mergeb. Polyphase mergec. Replacement selection

17. When can we use insertion sort?Insertion sort is useful only for small files or very nearly sorted

files.

18. How many passes are required fork-way merging?The number of passes required using k-way merging is [log k

(n/m)] because the N H S get k times as large in each pass.

19. Define max heap?A heap in which the parent has a larger key than the child's is

called a max heap.

20. Define min heap?A heap in which the parent has a smaller key than the child's is

called a min heap.

21. What is the need for hashing?

Page 56

Page 57: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Hashing is used to perform insertions, deletions and find in constant average time.

22. Define hash function?Hash function takes an identifier and computes the address of that

identifier in the hash table using some function.

23. List out the different types of hashing functions?The different types of hashing functions are,

a. The division methodb. The mind square methodc. The folding methodd. Multiplicative hashinge. Digit analysic

24. What are the problems in hashing?a. Collisionb. Overflow

25. What are the problems in hashing?When two keys compute in to the same location or address in the

hash table through any of the hashing function then it is termed collision.

Unit -5

1. Define Graph?A graph G consist of a nonempty set V which is a set of nodes of

the graph, a set E which is the set of edges of the graph, and a mapping from the set for edge E to a set of pairs of elements of V. It can also be represented as G=(V, E).

2. Define adjacent nodes?Any two nodes which are connected by an edge in a graph are

called adjacent nodes. For example, if and edge xÎE is associated with a pair of nodes (u,v) where u, v Î V, then we say that the edge x connects the nodes u and v.

3. What is a directed graph?A graph in which every edge is directed is called a directed graph.

4. What is a undirected graph?A graph in which every edge is undirected is called a directed

graph.

5. What is a loop?An edge of a graph which connects to itself is called a loop or sling.

Page 57

Page 58: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

6. What is a simple graph?A simple graph is a graph, which has not more than one edge

between a pair of nodes than such a graph is called a simple graph.

7. What is a weighted graph?A graph in which weights are assigned to every edge is called a

weighted graph.

8. Define out degree of a graph?In a directed graph, for any node v, the number of edges which

have v as their initial node is called the out degree of the node v.

9. Define indegree of a graph?In a directed graph, for any node v, the number of edges which

have v as their terminal node is called the indegree of the node v.

10. Define path in a graph?The path in a graph is the route taken to reach terminal node from

a starting node.

11. What is a simple path?A path in a diagram in which the edges are distinct is called a

simple path. It is also called as edge simple.

12. What is a cycle or a circuit?A path which originates and ends in the same node is called a

cycle or circuit.

13. What is an acyclic graph?A simple diagram which does not have any cycles is called an

acyclic graph.

14. What is meant by strongly connected in a graph?An undirected graph is connected, if there is a path from every

vertex to every other vertex. A directed graph with this property is called strongly connected.

15. When is a graph said to be weakly connected?When a directed graph is not strongly connected but the

underlying graph is connected, then the graph is said to be weakly connected.

16. Name the different ways of representing a graph?a. Adjacency matrixb. Adjacency list

17. What is an undirected acyclic graph?When every edge in an acyclic graph is undirected, it is called an

undirected acyclic graph. It is also called as undirected forest.

Page 58

Page 59: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

18. What are the two traversal strategies used in traversing a graph?

a. Breadth first searchb. Depth first search

20. What is a minimum spanning tree?A minimum spanning tree of an undirected graph G is a tree

formed from graph edges that connects all the vertices of G at the lowest total cost.

21. What is NP?NP is the class of decision problems for which a given proposed

solution for a given input can be checked quickly to see if it is really a solution.

QUICK SORT

It is known as Partition Exchange Sort It is an efficient sorting algorithm It is an example of Divide and Conquer algorithm Two phases

Partition phase Divides the work into half

Sort phase Conquers the halves!

Algorithm:

1. Pick an element, called a pivot, from the list.

2. Reorder the list so that all elements with values less than the pivot come before the

pivot, while all elements with values greater than the pivot come after the pivot

(equal values can go either way). After this partitioning, the pivot is in its final

position. This is called the partition operation.

3. Recursively  sort the sub-list of lesser elements and the sub-list of greater elements.

Given an array ‘x’ of n elements

• Choose an element ‘a’ from specific position within the array(first element is chosen a=x[0])

• The elements of ‘x’ are partitioned so that pivot element ‘a’ is placed in its position ‘j with condition

• Elements in position 0 through j-1 is less than or equal to pivot• Elements in position j+1 through n-1 is greater than pivot

– Quicksort two sub-arrays i.e., Repeat the same process with subarrays • x[0] to x[j-1] and x[j+1] to x[n-1]

– Final results is sorted elements.

Page 59

Page 60: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Given array of n integers to sort:

Partitioning Array:

Given a pivot, partition the elements of the array such that the resulting array consists of:

1. One sub-array that contains elements >= pivot 2. Another sub-array that contains elements < pivot

Step 1: Quick sort - Partition

Step 2: Quick sort - Partition

Step 3: Quick sort - Partition

Step 4: Quick sort - Partition

Page 60

Page 61: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Step 5: Quick sort - Partition

Step 6: Quick sort - Partition

Step 7: Quick sort - Partition

Page 61

Page 62: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Step 8: Quick sort - Partition

Step 9: Quick sort - Partition

Step 10: Quick sort - Conquer

Page 62

Page 63: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Implementation of Quick sort:

Quick sort – Partition function:

Page 63

Page 64: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Time Complexity: O(n2) – O(nlogn)

Space Complexity: O(n) - O(logn)

Advantages:

It is in-place since it uses only a small auxiliary stack. It requires only n log(n) time to sort n items. It has an extremely short inner loop This algorithm has been subjected to a thorough mathematical analysis, a very

precise statement can be made about performance issues.

Disadvantages:

It is recursive. Especially if recursion is not available, the implementation is extremely complicated.

It requires quadratic (i.e., n2) time in the worst-case. It is fragile i.e., a simple mistake in the implementation can go unnoticed and cause

it to perform badly.

Merge Sort*It is based on the divide and conquer method

Page 64

Page 65: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

*Merging is the process of combining two or more sorted files into a third sorted file

Technique:*Divide the file into sub-files of size 1*Merge adjacent pairs of files of n/2 files of size n*Repeat these process until there is only one file remaining of size n

Examples:10 38 28 12 6 14 2410 38 28 12 6 14 24 Dividing10 38 28 12 6 14 24 10 38 28 12 6 14 24

10 38 12 28 6 14 24

10 12 28 38 6 14 24 Conquering

Sorted list:6 10 12 14 24 28 38

Algorithm:Void merge split(int a[],int first,int last){ if(first<last) { Mid=(first+last)/2; Merge_split(a,first,mid); Merge_split(a,mid+1,last) Merge_sort(a,first,mid,mid+1,last) } } Void merge_sort(int a[],int f1,int l1,int f2,int l2) { i=f1; j=f2; while(i<=l1&&j<=l2) { if(a[i]<a[j])

b[k]=a[i++] else b[k]=a[j++]

k++; } While(i<=l1)

b[k++]=a[i++]; while(j<=l2) b[k++]=a[j++]; i=f1; j=0; while(i<=l2&&j<k)

Page 65

Page 66: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

a[i++]=b[j++]; }

Time Complexity: (n logn)

Space complexity: (n)- (n) extra space.

BUBBLE SORTIt is the simplest way of sorting method. In this type of sorting most values are used

and easy to handle.Technique:-

To pass through the file sequentially several times.Pass:-

Consist of comparing each element in the file with its successor.Compare x[i] with x[i+1] and interchange the root element if they are in proper order.

Let x be an array with elements 45,40,190,99,11.Pass 1:-

45 40 190 99 11x[0] is compared with x[1].45 > 40 interchange

40 45 190 99 11x[1] is compared with x[2].45 < 190 no need to interchange

40 45 190 99 11

x[2] is compared with x[3].190 > 90 interchange

40 45 99 190 11x[3] is compared with x[4].190 > 90 interchange

40 45 99 11 190After pass 1, the largest element is in its proper position in the array. (i.e) the no.

slowly bubbles upto its proper position.Pass 2:-

40 45 99 11 190x[0] is compared with x[1]40 < 45 no need to interchangex[1] is compared with x[2]45 < 99 no need to interchangex[2] is compared with x[3]99 < 11 interchange

40 45 11 99 190After pass 2, the 2nd largest no. bubbles to its position.

Pass 3:-40 45 11 99 190

x[0] is compared with x[1]

Page 66

Page 67: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

40 < 45 no need to interchangex[1] is compared with x[2]45 > 11 interchange

40 11 45 99 190After pass 3, the 3rd largest element is placed in its position.

Pass A:- a[0] is compared with a[1] 40 > 11 interchange

11 40 45 99 190After pass 4, all the elements are placed in its position.Each iteration places its new element into its proper position in a file.A file of n elemnets required not more than (n-1) iteration.Iteration 0: 45 40 99 190 11Iteration 1: 40 45 99 11 190Iteration 2: 40 45 11 99 190Iteration 3: 40 11 45 99 190Iteration 4: 11 40 45 99 190

Algorithm:void bubble(int x[],int n){ int i,j,temp; int flag=0;pass=0; for(j=0;j<n-1;j++) { flag=0; for(j=0;j<n-1;j++) { if(x[j]>x[j+1]) { temp=x[j]; x[j]=x[j+1]; x[j+1]=temp; }flag=1; pass++; } if(flag==0) break; }printf(“No. of pass %d”,pass); }EFFICIENCY:-

In pass 1, no. of comparisons are (n-1). In pass 2, no. of comparisons are (n-1). In pass 2, no. of comparison is (n-2). In final (n-1) pass, no. of comparisons are (n-1)+(n-2)+………..+2+1= ((n-1)n)/2TIME COMPLEXITY:-

The time complexity of bubble sort is O(n2).“Bubbling up” the largest element.

- Traverse a collection of elements.- Move form the front to the end.

Page 67

Page 68: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

- “Bubble” the largest value to the end using pair-wise comparisons & swapping.

INSERTION SORT(i) Simple insertion sort(ii) Shell sort(iii) Address calculation sort

(i) SIMPLE INSERTION SORT:-

This technique is very efficient if elements are very less. It is similar to the way librarian keeps the books in shelf in an increasing order.

Technique:-Consider an array of 10 elements to sort.

Steps 1:- Compare ith item with jth item. Steps 2:- Copy the item of the jth position in jth position.

Insertion sort is better than bubble sort. Consider the elements 24,6,2,12,18,8

Iteration 1:- Pass 1:- x[1] < x[0]

6 < 24 interchange6 24 2 12 18 8

Pass 2:- x[2] < x[1] 2 < 24 interchange

6 2 24 12 18 8 Pass 3:- x[3] < x[2]

12 < 24 interchange 6 2 12 24 18 8

Pass 4:- x[4] < x[3] 18 < 24 interchange

6 2 12 18 24 8 Pass 5:- x[5] < x[4] 8 < 24 interchange

6 2 12 18 8 24

Iteration 2:-6 2 12 18 8 24

x[1] < x[0] 2 < 6 interchange

2 6 12 18 8 24 x[2] < x[1]

12 > 6 no need to interchange x[3] < x[2] 18 > 12 no need to interchange x[4] < x[3]

8 < 18 interchange

Page 68

Page 69: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

2 6 12 8 18 24

Iteration 3:-2 6 12 8 18 24

x[0] < x[1]Pass 1:- Compare x[1] with x[0] x[1] < x[0] 24 < 6 interchange x: 6 24 2 12 18 8Pass 2:- x[2] with x[1] & x[1] with x[0]

x[2] < x[1] 2 < 24 interchange

6 2 24 12 18 8 x[1] < x[0]

2 < 6 interchangex: 2 6 24 2 18 8

Pass 3:- Compare x[3] with x[2], then x[2] with x[1], then x[1] with x[0] x[3] < x[2]

12 < 24 interchange x: 2 6 12 24 18 8 12 > 6 no interchange x[1] < x[0] 6 < 2 no interchange

Pass 4: x[4], x[3] 2 6 12 24 18 8

x[3], x[2] 2 6 12 18 24 8 x[2], x[1] x[1], x[0]

Pass 5:- x[5], x[4] 2 6 12 18 8 24 x[5], x[4] 2 6 12 8 18 24 x[5], x[4] 2 6 8 12 18 24 x[5], x[4] 2 6 8 12 18 24 x[5], x[4] 2 6 8 12 18 24

Heap Sort*Heap sort is a method in which a binary tree is used in this method heap is created using binary tree and then heap is sorted using priority queue.Technique:*Create a heap using binary tree*Sorting-sort the elements *Heap is almost a complete binary tree and it can be either ascending tree ,descending tree

Page 69

Page 70: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Descending Heap:*The content of the each node is less than or equal to the content of its father*Root node contains largest element and the path from the root to a leaf is deacending order.Ascending heap:*The content of each node is greater than or equal to the content of its father.*Root node contains smallest element and path from the to a leaf is ascending order

Consider the elements 25 57 48 38 10 91 84 33Step 1:Take 25 as the root node 25Step 2:take 57, 25 57Heap is //Left justified balanced tree

5725

Step 3: take 48, 57

25 48

Step 4: take 38,57

25 4838

Step 5: take 10,57

38 4825 10

Step 6: take 91, 57

38 4825 10 91

The heap is :91

38 5725 10 48

Step 7: take 84,91

38 8425 10 48 57

33

Heap is:

Page 70

Page 71: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

91 38 84

33 10 48 5725Descending heap is constructed .

Technique-Sorting: Sort the heap, by deleting the root node of a heap and store at the end of the array.Binary tree from should not be disturb the tree should remain a complete binary tree.Step 1:

91 38 84

33 10 48 5725

Step 2:

From the next level of root the greater value 84 is considered as root and the heap is rearranged as shown,

84 38 57

33 10 48 25

38 5733 10 48 25

Step 3: From the next level of root the greater value 57 is considered as root and the heap is rearranged as shown,

57 38 48

33 10 25

Step 4:

48 38 25

33 10

Step 5:38

33

Page 71

Page 72: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

25 10

Step 6: 33

25 10

Step 7: 25 10

Step 8:10

Algorithm:Algorithm heap (x,n) {

Repeat for k=1to n-1/*k=>child position*/

Item=x[k];//item to be insereted i=k//position I j=(i=1)/2// obtain parent position,

While parent exit and item >parent move dawn to position of childMake parent node as child obtain the position of new parentEnd while,

End for,Insert item into its child position.i->position of childj->position of parent {

forwhile i>0&&item>a[j] a[i]=a[j]; i=j; j=(i-1)1/2

end while a[i]=item;

end for}

Algorithm adjust(a,n)

Page 72

Page 73: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

{ item=a[0] //node to be inserted to created heap i=0; //position

i=2*j+1; //obtain left child While i<=n-1; //left child exist also

if(a[i]<a[j]) i=i+1 // obtain position to childEnd if

//if item less than the largest child if(item<a[i]) then

a[j]=a[i] //move largest child to parent position j=i; //makes largest child as parent i=2*j+1 //obtain position of left child for new parent

else break; //proper position found

}//insert item into parent postiona[j]=item;}

BINARY SEARCH TREE

Definition :

A binary tree that has the property that all elements in the left subtree of a node ‘n’ are less than the contents of ‘n’, and all the elements in the right subtree of ‘n’ are greater than or equal to the contents of n is called a Binary Search Tree(BST).

Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.

Key Notes:

The highest valued element in a BST can be found by traversing from the root in the right direction all along until a node with no right link is found (we can call that as the rightmost element in the BST).

The lowest valued element in a BST can be found by traversing from the root in the left direction all along until a node with no left link is found (we can call that as the leftmost element in the BST).

Search is straightforward in a BST. Start with the root and keep moving left or right using the BST property. If the key we are seeking is present, this search procedure will lead us to the key. If the key is not present, we end up in a null link.

If a binary search tree is traversed in inorder and the contents of each node are printed as the node is visited, the numbers are printed in ascending order.

Inorder traversal of a binary search tree always gives a sorted sequence of the values. This is a direct consequence of the BST property. This provides a way of sorting a given sequence of keys ……first, create a BST with these keys and then do an inorder traversal of the BST so created.

Page 73

Page 74: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Examples:

1)Simple Binary Search tree for the given list is as follows:78,65,4268,80,85

Another Example: The following tree is obtained by inserting the values 13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 by keeping in mind the BST property .

Various operations that can be performed on Binary Search tree are:1. Insertion of a node in a BST.2. Deletion of an element from the BST.3. Searching of an element in the BST.

Insertion:

For a standard insertion operation, we only need to search for the proper position that the element should be put in and replace NIL by the element. If there are n elements in the

Page 74

78

65

42

68

80

85

Page 75: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

binary search tree, then the tree contains (n+1) NIL pointers. Therefore, for the (n+1)th element to be inserted, there are (n+1) possible places available.

Example: Let us take the following tree.Now 55 has to be inserted in the following tree.

1. Compare 55 with the root node (80) 55<80 – Go to the left sub tree.

2. Compare 55 with the left child.55>50 - Go to right branch.

3.Since no element is present at that position 55 is inserted at that position .Before insertion:

After Insertion:

Algorithm:

To insert an element:

1. First look for its appropriate position in the Binary Search tree.

2. Compare it with each node of the tree.

Page 75

80

50

85

40

45

90

55

Page 76: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

3. If the value is greater than the current node, move to the right side of the root else move to the left of the current node.

Implementation:

void insert(node *root, node*new)

{

if(new->data<root->data)

{

if(root->left=NULL)

root->left=new;

else

insert(root->left, new);

}

if(new->data>root->data)

{

if(root->right==NULL)

root->right=new;

else

insert(root->right, new);

}

} Deletion:

There are several cases in a binary search tree for the deletion operation:

1. A node with no children (leaf node).2. A node with one child. 3. A node with two children.

Deletion of a Leaf node: This is the simplest deletion ,in which we set the left or right pointer of parent node as NULL.

Example: Before Deletion:

Page 76

10

Page 77: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

From the above tree ,we want to delete the node having value 6 we will set left pointer of its parent node as NULL. That is left pointer of node having value 8is set to NULL.

After Deletion:

Algorithm:

1.Search the parent of the leaf and the link to the leaf node as NULL.

2.Release the memory for the deleted node.

Deletion of a node with one child: Here the inorder successor is always copied at the position of a node being deleted.

Example: Before Deletion:

Page 77

8 20

6 15

22

Page 78: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Here if 8 has to be deleted. First copy the node 6 at the place of 8 and then set the node free.

After Deletion:

Algorithm:

1.Search the parent node to be deleted with only one child.

2.Assign the link of the parent node to be deleted.

3.Release the memory for the deleted node.

Deletion of a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Replace the value of N with the value of R, then delete R.

Example: Before Deletion:

Page 78

6

Page 79: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Here if 20 has to be deleted, we will have to copy the inorder successor of node 20 (i.e. 15)at its position and set the left pointer as NULL.

After Deletion:

Algorithm:

1. Search the parent of the node to be deleted with two children.

2. Copy the content of the inorder successor to the node to be deleted.

3. Delete the inorder successor node

a)if the inorder successor node has no child ,follow the steps of deleting a leaf node.

b)if the inorder successor node has one child follow the steps of deleting a node with one child.

4. Release the memory for the deleted node.

5. Replace the content of the node to be deleted with the copy of the content of the inorder successor node.

Page 79

Page 80: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Implementation:

void del(node*root, int key)

{

node *temp,*parent,*temp_succ;

temp=search(root, key,&parent);

/*Deleting a node with two children*/

if(temp->left!=NULL&&temp->right!=NULL)

{

parent=temp;

temp_succ=temp->right;

while(temp_succ->left!=NULL)

{

parent=temp_succ;

temp_succ=temp_succ->left;

}

temp->data=temp_succ->data;

parent->right=NULL;

printf(“Now Deleted it!”);

return;

}

/*Deleting a node having only one child*/

/*The node to be deleted has left child*/

if(temp->left!=NULL&&temp->right!=NULL)

{

if(parent ->left==temp)

parent->left=temp->left;

else

parent->right=temp->left;

temp=NULL;

free (temp);

printf(“Now deleted it !”);

return;

}

Page 80

Page 81: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

/*The node to be deleted has right child*/

if(temp->left!=NULL&&temp->right!=NULL)

{

if(parent ->left==temp)

parent->left=temp->right;

else

parent->right=temp->right;

temp=NULL;

free (temp);

printf(“Now deleted it !”);

return;

}

/*Deleting a node which is having no child*/

if(temp->left!=NULL&&temp->right!=NULL)

{

if(parent ->left==temp)

parent->left=NULL;

else

parent->right=NULL;

printf(“Now deleted it !”);

return;

}

}

Searching:

In Searching the node which we want to search is called a key node. The key node will be compared with each node starting from the root node if value of key node is greater than current node then we search for it on right sub branch otherwise on left sub branch. If we reach to leaf node and still we do not get the value of key node then we declare” Node is not present in the tree.”

Page 81

10

Page 82: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

In the above tree ,if we want to search for value 9.Then we will compare9 with the root node 10.As 9 is less than10 we will search on left sub branch. Now compare 9 with 5 ,but 9 is greater hence moved to the right branch and compared it has the value 9.Thus the desired node is searched.

Algorithm:

1.Check if, root node of BST is NULL, then print the tree is Empty.

2.Otherwise,compare the newnode data with the root node value for the following conditions.

a)If the content of the newnode = root node data

then the node is found.

b)If the content is less than root node.

1. Check left sub tree is NULL.

Then print ‘Search node ‘not found.

2.Otherwise consider the left child

as root and check the above condition.

c)If the content is greater than root node.

1. Check right sub tree is NULL.

Then print ‘Search node ‘not found.

2.Otherwise consider the right child

as root and check the above condition.

Page 82

9

5

4

Page 83: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

Implementation:

node*search(node*root, int key, node**parent)

{

node *temp;

temp=root;

while(temp!=NULL)

{

if(temp->data==key)

{

printf(“\nThe %d Element is present ”,temp->data);

return temp;

}

*parent=temp;

if(temp->data>key)

temp=temp->left;

else

temp=temp->right;

}

return NULL;

}

Time Complexity:

The average and worst case time complexity are O(log n).

Efficiency:

The cost of each operation is a function of the number of nodes it must access for a balanced tree, these operations are logarithmic, or O(log N)

The worst case (a fully degenerate tree) is O(N). If all permutations are equally likely, the average case is O(N log N).

Advantages: .BST involves less number of comparisons when compared to other method. The usage of memory will be reduced because of using Binary tree structure. Binary search trees are good if you do all three operation (insertion, deletion,

lookup) often and have enough data to justify the added burden of more complex structures and algorithms

Page 83

Page 84: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

AVL:

It is abbreviated as Adelsion Velski Lendis. AVL tree is a balanced binary tree in which the height of two sub trees of

every node never differ by more than one. Balance of a node is the height of the left sub-tree minus height of its right

sub-tree. The balance factor of a node is -1,0,1.

EG:

Balance factor of 5 = 2-1 = 1 Balance factor of 4 = 1 Balance factor of 7 = 0 Balance factor of 3 = 0 Therefore, the tree is an AVL tree.

Balance factor of 10 = 3-1 =2 Therefore, the tree is not an AVL tree.

REPERESENTATION: AVL follows properties of binary search tree. AVL is a binary search tree

with balance factor either 1,0 or -1. After insertion of any node, the balance factor becomes other than 1,0 or -

1 ,then the AVL property is violated. The nodes on that path has to be readjusted, the process of readjusting the

tree is known as rotation.

Insertion:

Four different cases of rotation is required after a insertion of a newnode.I. Insertion of newnode into left sub-tree of left child (LL).

II. Insertion of newnode into right sub-tree of left child (LR).III. Insertion of newnode of left sub-tree of right child (RL).

Page 84

Page 85: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

IV. Insertion of newnode of right sub-tree of right child (RR).

Rotation is a process of rebalancing the AVL tree to maintain the balance factor after insertion or deletion of a node.

Types:a) Single rotation

1. LL2. RR

b) Double rotation 1. LR2. RL

Different rotations: LL:

RR:

LR:

Page 85

Page 86: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

RL:

Rotations:I. Single rotations: left

After the insertion 90, the AVL property is violated,because the level of sub tree are same so single rotation is applied.

II. Single rotation:right

Page 86

Page 87: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

After the insertion of 20, to the AVL tree the property of AVL is violated so right rotation is applied.

III. Double rotation: LR

Page 87

Page 88: ECE DS Notes 2010 New

Data Structures and Algorithms SMVEC

After insertion of 35,the AVL property is violated so double rotation is applied.

IV. Double Rotation:(RL)

After the insertion of 70, the AVL property is violated so double rotation is applied.

Page 88