Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The...

25
FEST Data Structure & Algorithms Lab #1 Objective:- Introduction To Array and Its Related Operations An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. As discussed in the class/lecture room, there are different algorithms related to an array (Traversing, Insertion, Deletion, Modify, Sorting, Searching (Linear, Binary). Following algorithms helps you to understand and write programs. Traversing in Linear Array : Description: It means processing or visiting each element in the array exactly for one operation. Let ‘A’ is an array stored in the computer’s memory and we want to display the contents of ‘A’, then it has to be traversed i.e. by accessing and processing each element of ‘A’ exactly once. Linear array ‘A’ with lower boundary LB ( 0 in C++ ) and upper boundary ( UB = N - 1 in C++) where N is the number of values stored in the array. If the array is empty then N will be equal 0. SIZE is the total locations/positions available in array. This algorithm traverses ‘A’ applying process to each element of ‘A’. Rajkumar Chawla Page 1

Transcript of Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The...

Page 1: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Lab #1Objective:- Introduction To Array and Its Related Operations

An array is a series of elements of the same type placed in contiguous memory locationsthat can be individually referenced by adding an index to a unique identifier. Asdiscussed in the class/lecture room, there are different algorithms related to an array(Traversing, Insertion, Deletion, Modify, Sorting, Searching (Linear, Binary). Followingalgorithms helps you to understand and write programs.

Traversing in Linear Array :

Description: It means processing or visiting each element in the array exactly forone operation. Let ‘A’ is an array stored in the computer’s memory and we want todisplay the contents of ‘A’, then it has to be traversed i.e. by accessing and processingeach element of ‘A’ exactly once.

Linear array ‘A’ with lower boundary LB ( 0 in C++ ) and upper boundary ( UB =N - 1 in C++) where N is the number of values stored in the array. If the array is emptythen N will be equal 0. SIZE is the total locations/positions available in array. Thisalgorithm traverses ‘A’ applying process to each element of ‘A’.

Algorithm: (Traverse a Linear Array) Here A is an array has N elements storedin it, with lower bound LB=0 and upper bound UB= N - 1.1. K = LB and UB = N - 12. Repeat Steps 3 and 4 while K ≤ UB.3. Apply PROCESS to A[K].4. K = K+1.[End of Step 2 loop.]5. End.

Rajkumar Chawla Page 1

Page 2: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Insert an Item into Linear Array:

Description: Inserting refers to the addition of a new element in an array,say ‘A’. Inserting an element at the end of the array can be easily done. On theother hand, if an element is to be inserted at the beginning or in the middle of array‘A’, then the elements (from insertions point inclusively) must be moved downwardto new locations, to accommodate the new element. Assume, values inside the ‘A’are in sorted order and it is needed to insert the new item at such location in ‘A’ so thatthe sorted order of ‘A’ should not be disturbed. See the algorithm:

The following set of algorithms inserts a data element ITEM at Kth position in a lineararray.Here A is a Linear Array with SIZE locations, N is the number of total valuesstored in A and K is a positive integer (location where to insert) such that K<= N.This algorithm inserts an element ITEM into the Kth position in A.

Algorithm:

1. if N = SIZE then write: “Overflow, Array is Full. “ and End2. Get ITEM from user to be inserted in array[ Find location in sorted array ]3. Call Find_Location_To_Insert (A, N, K, ITEM)[ Above algorithm finds the location K where to insert ]4. Call INSERT (A, N, K, ITEM)5. End

Algorithm: Find_Location_To_Insert(A, N, K, ITEM)1. LB = 0 and UB = N – 12. Repeat Step-3 for K = LB to UB.3. If A[K] = ITEM then Exit Loop. [End of Step 2 loop.]4. return K. 5. End.

Algorithm: INSERT (A, N, K, ITEM)1. Set J = N - 1. [Initialize counter.]2. Repeat Step-3 and 4 while J≥K.3. Set A[J+1] = A[J]. [Move Jth element downward.]4. Set J = J-1. [Decrease counter.][End of Step 2 loop.]5. Set A[K] = ITEM. [Insert element.]6. Set N = N+1. [Reset N.]7. End.

Rajkumar Chawla Page 2

Page 3: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Delete an Item from Linear Array:

Description: Deletion refers to the operation of removing one of the elementfrom the array ‘A’. Deleting an item at the end of the array presents no difficulties.But, deleting an item from beginning or somewhere in the middle of array wouldrequire that each subsequent element be moved one location upward in order to fillup the array.The following algorithm deletes the Kthelement from a linear array A with Nvalues stored in it.Here A is a Linear Array with SIZE locations, N is the number of total values storedin A and K is a positive integer such that K<=N. This algorithm deletes the Kthelement from A.

Algorithm:1. If N = 0 then write: “Underflow. Array is Empty. “ and End2. Get ITEM from user to be deleted from array[ Find location in sorted array ]3. Call Find_Location_To_Delete(A, N, K, ITEM)4. If found Call DELETE (A, N, K, ITEM) [ if K = -1 then not found ]Else write: “Not Found in array”5. End

Algorithm: Find_Location_To_Delete(A, N, K, ITEM)1. Repeat Step 2 for I = LB to UB.2. If A[I] = ITEM then K = I and return K. [ Deletion from front or from middle][End of Step 2 loop.]3. K = -1 and return K. [ITEM Not found in array ]4. End.

Algorithm: DELETE (A, N, K, ITEM)1. Set ITEM = A[K].2. Repeat for J=K to N-1:Set A[J] = A[J+1] [Move J + 1 element upward.].[End of loop.]3. Set N = N-1. [Reset the number “N” of element in A.]4. End.

Lab Task:

Convert the above algorithms in C/C++

Rajkumar Chawla Page 3

Page 4: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Lab # 2

Strings Operations

Length The number of characters in a string is called its length. The function length(s) returns the length of string s.

concatenation Concatenation combines the characters of two strings. For example, concatenation of string s1 with string s2 results in a string containing characters of s1 followed by those of s2. Note that string terminator of s1 is replaced by the first character of s2, but string terminator of s2 is retained.

Substring Accessing a substring from a given string requires three pieces of information: a) The name of the string itself, (s)b) the position of the first character of the substring in the given string (ip) c) the length of the substring or the position of the last character of the substring. (len)

The function substring (s, ip, len) denotes the substring of a string s beginning in a position ip and having a length len.

I ndex The function index(T, P) is used to find the position where a string pattern P first appears in a given string text T. This is called pattern matching.

ALGORITHMS Algorithm A1: length(s) 1. Initialize len to 0. 2. Set a variable to the beginning index of string s. 3. Repeat the following step till the string terminator is encountered. 4. len = len +1 5. Exit

Algorithm A2: concatenate (s1, s2) 1. Initialize i = strlen(s1) 2. Initialize j = strlen(s2) 3. Initialize count =0; / * This segment copies characters of s2 into array s1 * / 4. Repeat steps 5 to 7 while count <= j 5. s1[i] = s2[count] 6. i = i + 1 7. count = count + 1

Rajkumar Chawla Page 4

Page 5: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

8. Exit

Algorithm A3: substring (s, ip, len) 1. Initialize i = ip and count = 0 2. Use an array “dest‟ to hold the required substring 3. Repeat steps 4 ,5 and 6 while count < len 4. dest[count] = s[i] 5. count = count +1 6. i = i + 1 7. Insert string terminator at end of dest 8. Exit

Algorithm A4: index(t, p) / * t and p are respectively lengths of strings T and P * /1. Initialize i = 0 and max = t – p + 1 2. Repeat steps 3 to 6 while i < max 3. Repeat for j = 0 to p – 1 4. If P[j] ≠ T[i+j] then goto step 6 5. Return index i and exit 6. i = i + 1 7. Return –1 for no match 8. Exit

Lab Tasks:

1. Implement the above algorithms in C/C++.

2. Design an algorithm that takes a string S and a char ‘a’ as input. It then displays the all occurrences of a in S.

Rajkumar Chawla Page 5

Page 6: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Lab # 03

Linear Search using a given Search Key in an unsorted

Theory

The linear search compares each element of the Linear Array ‘A’ which has N values in it with the search key until the search key is found. To determine that a value is not in the array, the program must compare the search key to every element in the array ‘A’. It is also called “Sequential Search” because it traverses the data sequentially to locate the element.

Algorithm: (Linear Search)LINEAR_SEARCH (A, N, SKEY)Here A is a Linear Array with N elements and SKEY is a given item of information to search. This algorithm finds the location of SKEY in A and if successful, it returns its location otherwise it returns -1 for unsuccessful. T is a variable that we use temporary.

1. Repeat step-2 for K = 0 to N-12. if(A [K] = SKEY) T = K K= N 3. If (k<N) return K [Successful Search]

else return -1 [Un-Successful]4. End.

Binary search on a list of elements stored in an array.

THEORY

Suppose DATA is an array that is sorted in increasing (or decreasing) numerical order or, equivalently, alphabetically. Then there is an extremely efficient searching algorithm, called binary search, which can be used to find the location LOC of a given ITEM of information in DATA.

The binary search algorithm applied to our array DATA works as follows: During each stage of algorithm, our search for ITEM is reduced to a segment of elements of DATA: DATA[BEG], DATA[BEG+1], DATA[BEG+2], . . ., DATA[END]

Note that the variables BEG and END denote, respectively, the beginning and end locations of the segment under consideration. The algorithm compares ITEM with the middle element DATA[MID] of the segment, where MID is computed as

MID = INT((BEG + END) / 2) (INT(A) refers to the integer value of A.)

Rajkumar Chawla Page 6

Page 7: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

If DATA[MID] = = ITEM, then the search is successful and we set LOC = MID. Otherwise a new segment of DATA is obtained as follows:

a) If ITEM < DATA[MID], then ITEM can appear only in the left half of the segment: DATA[BEG], DATA[BEG+1], . . . , DATA[MID-1] So we reset END = MID –1 and begin searching again.

b) If ITEM > DATA[MID], then ITEM can appear only in the right half of the segment: DATA[MID+1], DATA[MID+2], . . . , DATA[END] So we reset BEG = MID +1 and begin searching again.

Initially, we begin with the entire array DATA; i.e., we begin with BEG = 0 and END = N-1. If ITEM is not in DATA, then eventually we obtain BEG > END.

This condition signals that the search is unsuccessful, and in such a case we assign LOC = NULL. Here NULL is a value that lies outside the set of indices of DATA.

ALGORITHM Algorithm: BINSEARCH(DATA, ITEM)

1. Set BEG = 0, END = N-1 and MID = INT((BEG + END) / 2) 2. Repeat steps 3 and 4 while BEG <= END AND DATA[MID] ≠ ITEM 3. If ITEM < DATA[MID], then Set END = MID – 1, Else Set BEG = MID + 1 4. MID = INT((BEG + END) / 2) 5. If DATA[MID] = ITEM, then Set LOC = MID Else Set LOC = NULL 6. Exit

Lab Task:

1. Write a C program that makes use of the above algorithms as a function. Your program should input the array from the user.

Rajkumar Chawla Page 7

Page 8: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Lab #04

Sorting:

Sorting and searching are fundamental operations in computer science. Sorting refers to the operation of arranging data in some given order. Such as increasing/ascending or decreasing/descending order, with numeric data or alphabetically. There are so many ways / techniques to do sorting. Following aresome techniques:

Description: Sorting refers to the operation of re-arrangements of values inAscending or Descending order of the Linear Array ‘A’. Here ‘A’ is Linear Arrayand N is the number of values stored in A.

Algorithm: (Bubble Sort) BUBBLE (A, N)Here A is an Array with N elements stored in it. This algorithm sortsthe elements in A.

Step 1. Repeat Steps 2,3 for Pass = 1 to N – 1Step 2. Set Swapped = 0 and K = 0Step 3. Repeat while K < (N – Pass) (a) if A[ K ] > A[ K + 1] then Interchange A[ K ] and A[ K + 1 ] and Set Swapped = 1 [ End of if structure. ] (b) Set K = K + 1 [ End of inner loop of step-3. ] [ End of outer loop of step-1. ]Step 4. End

Insertion Sort

Description: Here ‘A’ is Linear Array and N is the number of values stored in A

Algorithm: (INSERTION SORT) INSERTION (A, N) [ Where A is an array and N is the number of values in the array ]Step 1. Repeat steps 2 to 4 for K=1,2,3, . . . . . N-1:Step 2. Set TEMP = A[K] and i =K-1.Step 3. Repeat while i >= 0 and TEMP < A[i] a) Set A[i+1] = A[i]. [Moves element forward.] b) Set i = i -1.[End of loop.]Step 4. Set A[i+1] =TEMP. [Insert element in proper place.][End of Step 2 loop.]Step 5. Return.

Selection Sort:

Rajkumar Chawla Page 8

Page 9: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Description: Here ‘A’ is Linear Array and N is the number of values stored in A.

Algorithm: SELECTION (A, N)

Step 1. Repeat steps 2, 3and 5 for K=0 to. N-2:Step 2. Set MIN = A[K] and LOC = K. [Initializes pointers.]Step 3. Repeat Step 4 for J=K+1, K+2, . . . . . N:Step 4. If MIN > A[J], then: MIN = A[J] and LOC = J.

Step 5. Set TEMP = A[K], A[K] = A[LOC] and A[LOC] = TEMP.[End of step 1 loop.]Step 6. Exit

Lab Task:

Task-1 Convert all algorithms into C/C++/Java programming.

Lab # 05

Rajkumar Chawla Page 9

Page 10: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Quick Sort:

AIM: Write a program to Sort values in Ascending / Increasing Order using QuickSort Technique in Linear Array:Description: Here ‘A’ is Linear Array and N is the number of valuesstored in A. Here, recursive function is going to use for QUICK SORT. For detailabout this algorithm, see the lecture notes written by Shahid Iqbal Lone, LecturerComputer College, Qassim University K.S.A.Quick sort is an algorithm of the divide-and-conquer type. That is, theproblem of sorting a set is reduced to the problem of sorting two smaller sets.

Algorithm: QUICKSORT (A, LEFT, RIGHT)1. If LEFT ≥ RIGHT, then: Return.2. Set MIDDLE = PARTITION (A, LEFT, RIGHT).3. Call QUICKSORT (A, LEFT, MIDDLE-1).4. Call QUICKSORT (A, MIDDLE+1, RIGHT).5. Return.

Algorithm: PARTITION (A, LEFT, RIGHT)1. Set X = A[LEFT].2. Set I = LEFT.3. Repeat for j = LEFT+1,LEFT+2, . . . . . RIGHTIf A[j] < X, then:Set i = i+1.SWAP (A[i], A[j]). [Interchange A[i] and A[j].]4. SWAP (A[i], A[LEFT]. [Interchange A[i] and A[LEFT].]5. Return i.

Lab Task:

Q#1. Convert the algorithm in to C /C++ programming.

Lab # 06

Rajkumar Chawla Page 10

Page 11: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Linked List:A linked list or one way list is a linear collection of data elements, called nodes, where the linear order is given by means of “pointers”. Each node is divided into two parts.

The first part contains the information of the element / node. The second part called the link field contains the address of the next node in the

list.

Example:

Description: Here LIST is a structure has two members (Info and Next), whereInfo is used to store the data and Next is a pointer used to hold the address of next node.HEAD is a pointer to LIST, points to the beginning/first element of the LIST. ITEM is thevalue needed to insert or delete in/from the LIST. The initial value of the HEAD is NULL,it means that initially LIST is empty. NewNode is pointer variable which holds theaddress of newly created LIST node.

Operations on Linked List:a) Creation of Link Listb) Traversing Linked List.c) Searching in Linked List.d) Insertion in Linked Liste) Deletion from Linked List

Algorithm to Linked List Creation

Algorithm: (ITEM), [ Here the initial value of FRONT & REAR are NULL ]

Step 1. Create dynamic NODE to store (Info and Next) for next node andstore its address into NewNode pointer[Insert ITEM in newly created Node for QUEUE.]Step 2. Set NewNode -> Info = ITEM and NewNode -> Next = NULLStep 3. If REAR = NULL then: Set REAR and FRONT both = NewNode [ First Node Enqueued ] Else Set REAR -> Next = NewNode Set REAR = NewNode[ End of If Structure ]Step 4. End.

Algorithm: (Traversing a Linked List) Let LIST be a linked list in memory. Thisalgorithm traverses LIST, applying an operation PROCESS to eachNode / element of the LIST. HEAD points to the first node of theLIST. Pointer variable CURR point to the node currently being

Rajkumar Chawla Page 11

Page 12: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

processed.

Step 1. Set CURR = HEAD. [Initializes pointer CURR.]Step 2. Repeat Steps 3 and 4 while CURR ≠ NULL.Step 3. Apply PROCESS to CURR -> INFO.Step 4. Set CURR = CURR -> NEXT [CURR now points to the next node.][End of Step-2 loop.]Step 5. End

Algorithm: INSERT( ITEM)NOTE: Here it is needed that all the time, LIST should remains in the sortedorder using Info part of the Node. To Insert / Enqueue a new node inthe LIST, first LIST will be searched (using Info of Nodes) to find itsLOCATION ( where to insert new Node). This exercise makes itpossible that every new node has the probability to insert at thebeginning, in the middle or at the end of LIST.CURR is a pointer points to the node currently being processed andPREV is a pointer pointing to previous node of the current node.[This algorithm adds NewNodes at any position (Top, in Middle OR at End)in the List ]

Step 1. Create a NewNode node for LIST in memoryStep 2. Set NewNode -> Info =ITEM. [Copies new data into INFO of new node.]Step 3. Set NewNode -> Next = NULL. [Copies NULL in NEXT of new node.].Step 4. If HEAD = NULL then: [ Condition to create the Linked List. ] HEAD=NewNode and return. [Add first node in list] [Add on top of existing list]Step 6. If NewNode-> Info < HEAD ->Info then:Set NewNode->NEXT = HEAD and HEAD = NewNode and return

[Search the LOCATION in Middle or at end. ][ Here CURR is the position where to insert and PREV points to previous node ofthe CURR node ]

Step 7. Set Prev = NULL and Set Curr = NULL;Step 8. Repeat for CURR =HEAD until CURR ≠ NULL after iteration CURR = CURR ->Nextc) if(NewNode->Info <= CURR ->Info) then: break the loopd) Set PREV = CURR;

[ end of loop of step-7 ][Insert after PREV node (in middle or at end) of the list]

Step 9. Set NewNode->NEXT = PREV ->NEXT andStep 10. Set PREV ->NEXT= NewNode.Step 11. Exit.

Lab Task:

Q#1. Convert all above algorithm in C/ C++ programming language.

Q#2. Write an algorithm that create a Link List in sorted manner?

Lab # 07Deletion Of Node

Rajkumar Chawla Page 12

Page 13: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Algorithm: DELETE( )LIST is a linked list in the memory. This algorithm gets ITEM from userand deletes the node where ITEM first appear in the LIST, otherwise itwrites “NOT FOUND”

Step 1. if HEAD =NULL then write: “Empty List” and return [Check for Empty List]Step 2. Get value for ITEM to delete it from LISTStep 3. if ITEM = HEAD -> Info then: [ Top node is to delete ]Set HEAD = HEAD -> Next and return

[Search the ITEM in Middle or at end to delete ][ Here CURR will be the position to delete and PREV pointer points to previousnode of the CURR node ]

Step 4. Set Prev = NULL and Set Curr = NULL;Step 5. Repeat for CURR = HEAD until CURR not = NULLand after every iteration update CURR = CURR ->Nexta) if(NewNode->Info = CURR ->Info) then: break the loopb) Set PREV = CURR;[ end of loop of step-5 ]

Step 6. if(CURR = NULL) then write : Item not found in the list and return[delete the current node from the list]

Set PPRE ->NEXT = CURR ->NEXTStep 7. End.

Two Way Link ListDifferent from a singly linked list, a doubly linked list allows us to go in both directions -- forward and reverse. Such lists allow for a great variety of quick update operations, including insertion and removal at both ends, and in the middle. A node in a doubly linked list stores two references -- a next link, which points to the next node in the list, and a prev link, which points to the previous node in the list.

It is usually convenient to add special nodes at both ends of a doubly linked list, a header node just before the head of the list, and a trailer node just after the tail of the list. These dummy or sentinel nodes do not store any elements. The header has a valid next reference by a null prev reference, while the trailer has a valid prev reference by a

Rajkumar Chawla Page 13

Page 14: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

null next reference. A linked list object would simply need to store references to these two sentinels and a size counter that keeps track of the number of elements (not counting sentinels) in the list

Insertion and Deletion Methods

Algorithm: INSERT( ITEM)NOTE: Here it is needed that all the time, LIST should remains in the sortedorder using Info part of the Node. To Insert / Enqueue a new node inthe LIST, first LIST will be searched (using Info of Nodes) to find itsLOCATION ( where to insert new Node). This exercise makes itpossible that every new node has the probability to insert at thebeginning, in the middle or at the end of LIST.CURR is a pointer points to the node currently being processed andPREV is a pointer pointing to previous node of the current node.[This algorithm adds NewNodes at any position (Top, in Middle OR at End)in the List ]Step 1. Create a NewNode node for LIST in memoryStep 2. Set NewNode -> Info =ITEM. [Copies new data into INFO of new node.]Step 3. Set NewNode -> Next = NULL. [Copies NULL in NEXT of new node.].Step 4. If HEAD = NULL then: [ Condition to create the Linked List. ]Step 5 HEAD=NewNode and return. [Add first node in list][Add on top of existing list]Step 6. If NewNode-> Info < HEAD ->Info then:Set NewNode->NEXT = HEAD and HEAD = NewNode and return

[Search the LOCATION in Middle or at end. ][ Here CURR is the position where to insert and PREV points to previous node ofthe CURR node ]

Step 7. Set Prev = NULL and Set Curr = NULL;Step 8. Repeat for CURR =HEAD until CURR ≠ NULL after iteration CURR = CURR ->Nextc) if(NewNode->Info <= CURR ->Info) then: break the loopd) Set PREV = CURR;

[ end of loop of step-7 ][Insert after PREV node (in middle or at end) of the list]

Step 9. Set NewNode->NEXT = PREV ->NEXT andStep 10. Set PREV ->NEXT= NewNode.Step 11. Exit.

Lab # 08

Deletion In Two Way Link List

Rajkumar Chawla Page 14

Page 15: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Algorithm: DELETE( )LIST is a linked list in the memory. This algorithm gets ITEM from userand deletes the node where ITEM first appear in the LIST, otherwise itwrites “NOT FOUND”Step 1. if HEAD =NULL then write: “Empty List” and return [Check for Empty List]Step 2. Get value for ITEM to delete it from LISTStep 3. if ITEM = HEAD -> Info then: [ Top node is to delete ]Set HEAD = HEAD -> Next and return[Search the ITEM in Middle or at end to delete ][ Here CURR will be the position to delete and PREV pointer points to previousnode of the CURR node ]Step 4. Set Prev = NULL and Set Curr = NULL;Step 5. Repeat for CURR = HEAD until CURR not = NULLand after every iteration update CURR = CURR ->Nexta) if(NewNode->Info = CURR ->Info) then: break the loopb) Set PREV = CURR;[ end of loop of step-5 ]Step 6. if(CURR = NULL) then write : Item not found in the list and return[delete the current node from the list]Set PPRE ->NEXT = CURR ->NEXTStep 7. End.

Lab Task:

Q#1. Convert all algorithms of Lab 7 & 8 in C / C++ programming.

Lab # 09

Rajkumar Chawla Page 15

Page 16: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Binary Trees Trees are one of the most important data structures in computer science. They come in many forms. They provide natural representations for many kinds of data that occur in applications, and they are useful for solving a wide variety of algorithmic problems. A tree is a collection of elements called nodes, one of which is distinguished as a root, with a relation (“parenthood”) that places a hierarchical structure on the nodes. A node, like an element of a list, can be of whatever type we wish. A structure with a unique starting node (the root), in which each node is capable of having at most two child nodes, and in which a unique path exists from the root to every other node is called a binary tree.

A root

B C

D E F

G H I J

A binary tree has a natural implementation in linked storage. In the implementation to follow, the pointer variable root points to the root of the tree. With this pointer variable, it is easy to recognize an empty binary tree as precisely the condition root = NULL, and to create a new, empty binary tree we need only assign its root pointer to NULL. One of the most important operations on a binary tree is traversal, moving through all the nodes of the binary tree, visiting each one in turn. As for traversal of other data structures, the action we shall take when we visit each node will depend on the application. For lists, the nodes come in a natural order from first to last, and traversal follows the same order. For trees, however, there are many different orders in which we can traverse all the nodes. Let V, L and R respectively represent visiting root, traversing left subtree, and traversing right subtree. There are three standard traversal orders.

One of the most important operations on a binary tree is traversal, moving through all the nodes of the binary tree, visiting each one in turn. As for traversal of other data structures, the action we shall take when we visit each node will depend on the application. For lists, the nodes come in a natural order from first to last, and traversal follows the same order. For trees, however, there are many different orders in which we can traverse all the nodes. Let V, L and R respectively represent visiting root, traversing left subtree, and traversing right subtree.

There are three standard traversal orders.

1. PREorder: V L R (Vertices, Left Side, Right Side)2. INorder: L V R (Left Side, Vertices, Right Side)3. POSTorder: L R V (Left Side, Right Side, Vertices)

Rajkumar Chawla Page 16

Page 17: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Algorithm: PREORDER (pRoot)First time this function is called by passing original ROOT into pRoot.Here pRoot is pointers pointing to current root. This algorithm does apreorder traversal of TREE, applying by recursively calling samefunction and updating proot to traverse in a way i.e. (NLR) Node,Left, Right.1. If (pRoot NOT = NULL) then: [ does child exist ?]a) Apply PROCESS to pRoot-> info. [ e.g. Write: pRoot -> info ][ recursive call by passing address of left child to update pRoot]b) PREORDER (pRoot -> Left)[ recursive call by passing address of right child to update pRoot]c) PREORDER( pRoot -> Right)[End of If structure.]2. End.

Algorithm: INORDER (pRoot)First time this function is called by passing original ROOT into pRoot.Here pRoot is pointers pointing to current root. This algorithm does aInorder traversal of TREE, applying by recursively calling same functionand updating proot to traverse in a way i.e. (LNR) Left, Node, Right.1. If (pRoot NOT = NULL) then: [ does child exist ?][ recursive call by passing address of left child to update pRoot]a) INORDER (pRoot -> Left)b) Apply PROCESS to pRoot-> info. [ e.g. Write: pRoot -> info ][ recursive call by passing address of right child to update pRoot]c) INORDER ( pRoot -> Right)[End of If structure.]2. End.

Lab # 10Algorithm: POSTORDER (pRoot)First time this function is called by passing original ROOT into pRoot.Here pRoot is pointers pointing to current root. This algorithm does a

Rajkumar Chawla Page 17

Page 18: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

PostOrder traversal of TREE, applying by recursively calling samefunction and updating proot to traverse in a way i.e. (LRN) Left, Right,Node.1. If (pRoot NOT = NULL) then: [ does child exist ?][ recursive call by passing address of left child to update pRoot]a) POSTORDER (pRoot -> Left)[ recursive call by passing address of right child to update pRoot]b) POSTORDER ( pRoot -> Right)c) Apply PROCESS to pRoot-> info. [ e.g. Write: pRoot -> info ][End of If structure.]2. End.

Binary search tree. Removing a node

Remove operation on binary search tree is more complicated, than add and search. Basically, in can be divided into two stages:

search for a node to remove; if the node is found, run remove algorithm.

Remove algorithm in detail

Now, let's see more detailed description of a remove algorithm. First stage is identical to algorithm for lookup , except we should track the parent of the current node. Second part is more tricky. There are three cases, which are described below.

1. Node to be removed has no children.

This case is quite simple. Algorithm sets corresponding link of the parent to NULL and disposes the node.

Example. Remove -4 from a BST.

2. Node to be removed has one child.

It this case, node is cut from the tree and algorithm links single child (with it's subtree) directly to the parent of the removed node.

Rajkumar Chawla Page 18

Page 19: Data Structure & Algorithms Web vieware in sorted order and it is needed to insert the new ... The function substring (s, ip, ... There are so many ways / techniques to do sorting.

FEST Data Structure & Algorithms

Example. Remove 18 from a BST.

Rajkumar Chawla Page 19