Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures 1.

Similar presentations


Presentation on theme: "Data Structures 1."— Presentation transcript:

1 Data Structures 1

2 Organizational Details
Class Meeting: 4:00-6:45pm, Tuesday, Room SCIT215 Instructor: Dr. Igor Aizenberg Office: Science and Technology Building, 115 Phone ( ) Office hours: Wednesday, Thursday, Friday – 2-00 pm Monday: by appointment Class Web Page: 2

3 Dr. Igor Aizenberg: self-introduction
MS in Mathematics from Uzhgorod National University (Ukraine), 1982 PhD in Computer Science from the Russian Academy of Sciences, Moscow (Russia), 1986 Areas of research: Artificial Neural Networks, Image Processing and Pattern Recognition About 100 journal and conference proceedings publications and one monograph book Job experience: Russian Academy of Sciences ( ); Uzhgorod National University (Ukraine, and ); Catholic University of Leuven (Belgium, ); Company “Neural Networks Technologies” (Israel, ); University of Dortmund (Germany, ); National Center of Advanced Industrial Science and Technologies (Japan, 2004); Tampere University of Technology (Finland, ); Texas A&M University-Texarkana, from March, 2006 3

4 Text Book "Data Structures" by Richard F. Gilberg & Behrouz A. Forouzan, 2nd Edn., Thomson Course Technology, 2006, ISBN 13: ; ISBN-10: 4

5 Control Exams (open book, open notes): Midterm 1: October 7, 2007
Midterm 2: November 4, 2007 Final Exam: December 9, 2007 Homework 5

6 Grading Grading Method Homework and preparation: 10%
Midterm Exam 1: 25% Midterm Exam 2: 30% Final Exam: % Grading Scale: 90%+  A 80%+  B 70%+  C 60%+  D less than 60%  F 6

7 What we will study? Algorithms and their implementation
The abstract data type Recursion Stacks and Queues Linear lists Trees Binary Search Trees Heaps 7

8 What we have to consider before we will start to study?
What is the Computer Science? Why we need to study data structures? A place of data structures within the Computer Science. 8

9 Computer Science and Data Structures
Organization of data processing and methods of data processing are a subject of Computer Science. A Data Structure is a collection of data organized in some logical pre-defined way. Studying Computer Science you will study different methods of data processing. Where is the initial point of this branch of science? 9

10 Historical Overview “Zero Generation”: Mechanical Computers ( ) Blez Pascal ( ), 1642, the first mechanical computer for addition and subtraction 10

11 Historical Overview “Zero Generation”: Mechanical Computers ( ) Gottfried Wilhelm von Leibniz ( ), 1672, the first mechanical computer for addition, subtraction, multiplication and division 11

12 Historical Overview “Zero Generation”: Mechanical Computers ( ) Charls Babbige ( ), 1834 Henry Babbige, 1888 “The Analytical Machine” – the first programmable computer 12

13 Historical Overview “Zero Generation”: Mechanical Computers ( ) Ada Augusta Lovelase ( ), 1843 The first programmer in the world, developed the first programming language in the world and the first software for the Babbige’s computer 13

14 Historical Overview Input and Control Device 512 Bytes Memory
The 1st generation electronic computers ( ) Input and Control Device 512 Bytes Memory 14

15 Cybernetics Cybernetics is the study of communication and control, typically involving regulatory feedback, in living organisms, in machines and organisations and their combinations, for example, in sociotechnical systems, computer controlled machines such as automata and robots. 15

16 Cybernetics Norbert Wiener ( ) is a founder of Cybernetics (1948). He coined the term "cybernetics" in his book “Cybernetics or Control and Communication in the Animal and the Machine” (MIT Press, 1948), widely recognized as one of the most important books of contemporary scientific thinking. 16

17 Data processing Control and feedback in any computer controlled system (including a computer itself) are reduced to analysis and transmission of different data. To analyze the corresponding data, those methods that can be presented in mathematical and logical description are used. Organization of data processing and methods of data processing are a subject of Computer Science. 17

18 Algorithm An algorithm is a finite set of well-defined instructions for accomplishing some task which, given an initial state, will terminate in a defined end-state. To develop any algorithm, it is necessary to know, how the corresponding task can be solved. 18

19 Types of Algorithms Linear algorithm consists of a sequence of unconditional straightforward steps. Loop is a group of steps that are repeated until some condition will not be satisfied. Nested Loop is a loop containing another loop (loops). Branching algorithm consists of a number of subsequences that can be taken depending on some condition (conditions). 19

20 Algorithm In Computer Science and Engineering flowcharts are often used to graphically represent algorithms. 20

21 Algorithms and Programming Languages
To utilize any algorithm using a computer, we have to develop a program using a programming language. Low-level language (assembly language) is a language of machine instructions. High-level language is a language, which is closer to our natural language. A program is implementation of the algorithm in a form acceptable for a computer. 21

22 Data Structures Any computer program serves some kind of data processing. Even those programs that do not compute anything (for instance, a program that copying a file from one location to another one) operate with some data. To access these data and to collect the resulting data, it is necessary to organize them in some reasonable structures. 22

23 Data Structures The simplest data structures are: a simple variable and a constant. Other data structures are: arrays, records, lists, trees, stacks, queues, etc.. Data structures are organized similarly in all the programming languages. The latter means that data structures can be studied independently of a particular programming language. Knowing data structures, it is easier to learn different programming languages. 23

24 Main Notions and Definitions.
Abstract Data Type Data Structures. Main Notions and Definitions.

25 Atomic Data 25

26 Data Structure A Data Structure is an aggregation of atomic and composite data into a set with defined relationships. Structure means a set of rules that holds the data together. Taking a combination of data and fit them into such a structure that we can define its relating rules, we create a data structure. 26

27 Composite Data Structures
27

28 Data Structure is: A combination of elements in which each is either a data type or another data structure A set of associations or relationships involving the combined elements 28

29 Data Structures: Properties
Most of the modern programming languages support a number of data structures. In addition, modern programming languages allow programmers to create new data structures for an application. Data structures can be nested. A data structure may contain other data structures (array of arrays, array of records, record of records, record of arrays, etc.) 29

30 Some Data Structures 30

31 Pseudocode Pseudocode is a pseudo programming language, which is commonly used to define algorithms Pseudocode is a natural language-like representation of the algorithm logic Its structure is close to the structure of the most high level programming languages, but it is free from many unnecessary details 31

32 Data Structures: A Pseudocode Approach with C
32

33 Data Structures: A Pseudocode Approach with C
33

34 The Abstract Data Type (ADT)
The concept of abstraction means: We know what a data type can do How it is done is hidden for the user With an ADT users are not concerned with how the task is done but rather with what it can do. 34

35 ADT: Example The program code to read/write some data is ADT. It has a data structure (character, array of characters, array of integers, array of floating-point numbers, etc.) and a set of operations that can be used to read/write that data structure. 35

36 The Abstract Data Type (ADT)
The Abstract Data Type (ADT) is: A data declaration packaged together with the operations that are meaningful for the data type. In other words, we encapsulate the data and the operations on the data, and then we hide them from the user. Declaration of data Declaration of operations Encapsulation of data and operations 36

37 The Abstract Data Type (ADT)
All references to and manipulation of the data in a structure must be handled through defined interfaces to the structure. Allowing the application program to directly reference the data structure is a common fault in many implementations. It is necessary for multiply versions of the structure to be able to coexist. We must hide the implementation from the user while being able to store different data. 37

38 38

39 ADT Operations Data are entered, accessed, modified and deleted through the external interface, which is a “passageway” located partially “in” and partially out of the ADT. Only the public functions are accessible through this interface. For each ADT operation there is an algorithm that performs its specific task. 39

40 Typical ADTs: Lists Stacks Queues Trees Heaps Graphs 40

41 1-4 ADT Implementations There are two basic structures we can use to
implement an ADT list: arrays and linked lists. In this section we discuss the basic linked-list implementation. 41

42 Array Implementations
In an array, the sequentiality of a list is maintained by the order structure of elements in the array (indexes). Although searching an array for an individual element can be very efficient, insertion and deletion of elements are complex and inefficient processes. 42

43 Linked Lists A Linked List is an ordered collection of data in which each element contains the location of the next element or elements. In a linked list, each element contains two parts: data and one or more links. The data part holds the application data – the data to be processed. Links are used to chain the data together. They contain pointers that identify the next element or elements in the list. 43

44 Linear and non-linear Linked Lists
In linear linked lists, each element has only zero or one successor. In non-linear linked lists, each element can have zero, one or more successors. 44

45 45

46 Nodes A node is a structure that has two parts: the data and one or more links. The nodes in a linked list are called self-referential structures. In such a structure, each instance of the structure contains one or more pointers to other instances of the same structural type. 46

47 Nodes The data part in a node can be a single field, multiple fields, or a structure that contains several fields, but it always acts as a single field. 47

48 48

49 Linked Lists vs. Arrays The major advantage of the linked list over the array is that data are easily inserted and deleted. It is not necessary to shift elements of a linked list to make room for a new elements or to delete an element. However, because the elements are no longer physically sequenced in a linked list, we are limited to sequential searches. 49

50 1-5 Generic Code for ADT In this section we discuss and provide examples of two tools that are required to implement an ADT. Pointer to Void Pointer to Function 50

51 Generic Code In data structures we need to create generic code for abstract data types. Generic code allows us to write one set of code and apply it to any data type. For example, we can write generic functions to implement a stack structure. We can then use the generic functions to implement an integer stack, a float stack, etc. 51

52 Data Pointer A pointer is a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address. Obtaining the value that a pointer refers to is called dereferencing the pointer. 52

53 Pointer to void Casting of the pointer is its connection with particular data type. Major programming languages are strongly typed. This means that operations such as assign and compare must use compatible types or be cast to compatible types. The only exception is the pointer to void, which can be assigned without a cast. This means that a pointer to void is a generic pointer that can be used to represent any data type. 53

54 Pointer to void 54

55 Pointer to void 55

56 Pointer to void Important remark: a pointer to void cannot be dereferenced unless it is cast. In other words, we cannot use *p without casting (without connection of the pointer with particular data type). 56

57 57

58 intPtr = (int*)malloc (sizeof (int))
Function malloc This function in C (a similar function is presented in all modern programming languages) returns a pointer to void. This function is used to dynamically allocate any type of data. This is a generic function that returns a pointer to void (void*). It can be used for returning a pointer to any data type. For example, a pointer to an integer can be created using intPtr = (int*)malloc (sizeof (int)) 58

59 Pointer to Node 59

60 60

61 61

62 (Continued) 62

63 63

64 64

65 Homework Sections 65

66 Pointers (Continuation) 66

67 Data Pointer A pointer is a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address. Obtaining the value that a pointer refers to is called dereferencing the pointer. 67

68 Pointer to void Major programming languages are strongly typed. This means that operations such as assign and compare must use compatible types or be cast to compatible types. The only exception is the pointer to void, which can be assigned without a cast. This means that a pointer to void is a generic pointer that can be used to represent any data type. 68

69 Pointer to void 69

70 Pointer to void 70

71 Pointer to void Important remark: a pointer to void cannot be dereferenced unless it is cast. In other words, we cannot use *p without casting (without connection of the pointer with particular data type). 71

72 intPtr = (int*)malloc (sizeof (int))
Function malloc This function in C (a similar function is presented in all modern programming languages) returns a pointer to void. This function is used to dynamically allocate any type of data. This is a generic function that returns a pointer to void (void*). It can be used for returning a pointer to any data type. For example, a pointer to an integer can be created using intPtr = (int*)malloc (sizeof (int)) 72

73 Pointer to Node 73

74 74

75 (Continued) 75

76 76

77 77

78 78

79 79

80 (Continued) 80

81 Pointer to Function Functions in our program occupy memory. The name of the function is a pointer constant to its first byte of memory. To declare a pointer to function, we code it as if it was a prototype definition, with the function pointer in parentheses. 81

82 82

83 Example: function larger
This generic function will return a larger value of two values to be compared To use a larger function as a generic one, we will need to write a compare function for each particular data type. A compare function will return either a positive or negative flag value depending on which value in a compared pair is larger: the first one or the second one. 83

84 84

85 85

86 86

87 87

88 88

89 89

90 90

91 Algorithm Efficiency Big-O Notation 91

92 What is the algorithm’s efficiency
The algorithm’s efficiency is a function of the number of elements to be processed. The general format is where n is the number of elements to be processed. 92

93 The basic concept When comparing two different algorithms that solve the same problem, we often find that one algorithm is an order of magnitude more efficient than the other. A typical example is a famous Fast Fourier Transform algorithm. It requires NxlogN multiplications and additions, while a direct Fourier Transform algorithm requires N2 multiplications and additions. 93

94 The basic concept If the efficiency function is linear then this means that the algorithm is linear and it contains no loops or recursions. In this case, the algorithm’s efficiency depends only on the speed of the computer. If the algorithm contains loops or recursions (any recursion may always be converted to a loop), it is called nonlinear. In this case the efficiency function strongly and informally depends on the number of elements to be processed. 94

95 Linear Loops The efficiency depends on how many times the body of the loop is repeated. In a linear loop, the loop update (the controlling variable) either adds or subtracts. For example: for (i = 0; i < 1000; i++) the loop body Here the loop body is repeated 1000 times. For the linear loop the efficiency is directly proportional to the number of iterations, it is: 95

96 Logarithmic Loops Multiply loop Divide loop
In a logarithmic loop, the controlling variable is multiplied or divided in each iteration For example: Multiply loop Divide loop for (i=1; i<=1000; i*=2) for (i=1000; i<=1; i /=2) the loop body the loop body For the logarithmic loop the efficiency is determined by the following formula: 96

97 97

98 Linear Logarithmic Nested Loop
for (i=1; i<=10; i++) for (j=1; j<=10; j *=2) the loop body The outer loop in this example adds, while the inner loop multiplies A total number of iterations in the linear logarithmic nested loop is equal to the product of the numbers of iterations for the external and inner loops, respectively (10log10 in our example). For the linear logarithmic nested loop the efficiency is determined by the following formula: 98

99 Quadratic Nested Loop for (i=1; i<10; i++) for (j=1; j<10; j ++)
the loop body Booth loops in this example add A total number of iterations in the quadratic nested loop is equal to the product of the numbers of iterations for the external and inner loops, respectively (10x10=100 in our example). For the quadratic nested loop the efficiency is determined by the following formula: 99

100 Dependent Quadratic Nested Loop
for (i=1; i<10; i++) for (j=1; j<i; j ++) the loop body The number of iterations of the inner loop depends on the outer loop. It is equal to the sum of the first n members of an arithmetic progression: (n+1)/2 A total number of iterations in the quadratic nested loop is equal to the product of the numbers of iterations for the external and inner loops, respectively (10x5=50 in our example). For the dependent quadratic nested loop the efficiency is determined by the following formula: 100

101 Big-O notation In general, the number of statements executed in the function for n elements of data is a function of the number of elements expressed as f(n). Although the equation derived for a function may be complex, a dominant factor in the equation usually determines the order of magnitude of the result. This factor is a big-O, as in “on the order of”. It is expressed as O(n) . 101

102 Big-O notation The big-O notation can be derived from f(n) using the following steps (pp ): In each term set the coefficient of the term to 1. Keep the largest term in the function and discard the others. Terms are ranked from lowest to highest: log n, n, n log n, n2, n3,…, nk,…2n,…, n! For example, 102

103 103

104 104

105 105

106 106

107 Add two matrices In this algorithm, we see that for each element in a raw, we add all the elements in a column. This means that we have a quadratic loop here and the efficiency of the algorithm is O(n2) 107

108 108

109 109

110 110

111 Multiply two matrices In this algorithm, we see three nested loops. Because each loop starts at the first element, we have a cubic loop and the efficiency of the algorithm is O(n3) 111

112 Homework Sections 1.5-1.8 Exercises (Section 1.9): 2, 6, 7, 8, 20, 21
112

113 RECURSION 113

114 Two approaches to writing repetitive algorithms:
Iteration Recursion Recursion is a repetitive process in which an algorithm calls itself. Usually recursion is organized in such a way that a subroutine calls itself or a function calls itself 114

115 Factorial – a case study
The factorial of a positive number is the product of the integral values from 1 to the number: 115

116 Factorial: Iterative Algorithm
A repetitive algorithm is defined iteratively whenever the definition involves only the algorithm parameter (parameters) and not the algorithm itself. 116

117 Factorial: Recursive Algorithm
A repetitive algorithm uses recursion whenever the algorithm appears within the definition itself. 117

118 Recursion: basic point
The recursive solution for a problem involves a two-way journey: First we decompose the problem from the top to the bottom Then we solve the problem from the bottom to the top. 118

119 Factorial (3): Decomposition and solution
119

120 120

121 121

122 122

123 Designing recursive algorithms
Each call of a recursive algorithm either solves one part of the problem or it reduces the size of the problem. The general part of the solution is the recursive call. At each recursive call, the size of the problem is reduced. 123

124 Designing recursive algorithms
The statement that “solves” the problem is known as the base case. Every recursive algorithm must have a base case. The rest of the algorithm is known as the general case. The general case contains the logic needed to reduce the size of the problem. 124

125 Designing recursive algorithms
Once the base case has been reached, the solution begins. We now know one part of the answer and can return that part to the next, more general statement. This allows us to solve the next general case. As we solve each general case in turn, we are able to solve the next-higher general case until we finally solve the most general case, the original problem. 125

126 Designing recursive algorithms
The rules for designing a recursive algorithm: First, determine the base case. Then determine the general case. Combine the base case and the general cases into an algorithm 126

127 Designing recursive algorithms
Each recursive call must reduce the size of the problem and move it toward the base case. The base case, when reached, must terminate without a call to the recursive algorithm; that is, it must execute a return. 127

128 Limitations of Recursion
Recursion should not be used if the answer to any of the following questions is no: Is the algorithm or data structure naturally suited to recursion (tree is the first choice) ? Is the recursive solution shorter and more understandable? Does the recursive solution run within acceptable time and space limits? As a general rule, recursive algorithms should be effectively used only when their efficiency is logarithmic. 128

129 Example-Problem Assume that we are reading data from the keyboard and need to print the data in reverse. The easiest formal way to print the list in reverse is to write a recursive algorithm. 129

130 Solution It should be obvious that to print the list in reverse, we must first read all of the data. If we print before we read all of the data, we print the list in sequence. If we print after we read the last piece of data - that is, if we print it as we back out of the recursion – we print it in reverse sequence. The base case, therefore, is that we have read the last piece of data. Similarly, the general case is to read the next piece of data. 130

131 Implementation 131

132 132

133 Analysis Is the algorithm or data structure naturally suited to recursion? A list, such as data read from the keyboard, is not naturally recursive structure. Moreover, the algorithm is not a logarithmic algorithm. Is the recursive solution shorter and more understandable? Yes Does the recursive solution run within acceptable time and space limits? The number of iterations in the traversal of a list can become quite large because the algorithm has a linear efficiency - O(n). 133

134 Example-Problem Determine the greatest common divisor (GCD) for two numbers. Euclidean algorithm: GCD (a,b) can be recursively found from the formula 134

135 Pseudocode Implementation
135

136 C implementation 136

137 137

138 138

139 Example-Problem Generation of the Fibonacci numbers series.
Each next number is equal to the sum of the previous two numbers. A classical Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, … The series of n numbers can be generated using a recursive formula 139

140 140

141 (Continued) 141

142 142

143 143

144 Example-Problem Prefix to Postfix conversion of an arithmetic expression. Prefix: + A B operator comes before the operands Infix: A + B operator comes between the operands Postfix: A B + operator comes after the operands The basic concept is to convert the expression like *AB to the one AB* To keep the algorithm as simple as possible, we assume that each operand is only one character and there are only four operators +, -, *,/ 144

145 Decomposition of (A*B+C)-E/F
145

146 146

147 147

148 Homework Chapter 2 Exercises 1, 2, 3 (pp. 72-73).
Problems 7, 8 (p. 74) 148

149 STACKS

150 Linear Lists A Linear List is a list in which each element has a unique successor. In a restricted linear list, addition and deletion of data are restricted to the ends of the list. In a general linear list, addition and deletion of data are allowed everywhere.

151 Stack A stack is a linear list in which additions and deletions of data are restricted to one end, called the top. If we insert a data series into a stack and then remove it, the order of data is reversed. This property is known as the last in – first out.

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174 Homework Exercises 1, 2 (pp ) Problem 9 (p.141)

175 Stacks (Continuation) Applications

176 Parse Parentheses

177

178 Infix to Postfix Transformation
Infix to Postfix transformation is a very important part of preprocessing of the source codes that are written in high-level languages. This transformation separates operands from operators

179 Infix to Postfix Transformation
A * B  AB* Which transformation is correct? A*B+C  ? ABC*+ A*B+C  ?  AB*C+ To ensure a correct representation, a precedence rule must be taken into account Thus, the second representation is correct

180 Infix to Postfix Transformation
The simplest visible solution is to push all the operators into the stack and then to pop the stack. However, this will work only for the simplest expression with the two operands A*B  AB* This will not work for the expression with more than two operands A+B*C ≠ ABC+* because a precedence rule is not taken into account in this solution. ABC+*  A*(B+C), but we need to represent A+B*C, that is we need to obtain the representation ABC*+

181 Infix to Postfix Transformation
Let us obtain A+B*C  ABC*+ Expression Stack Copy operand A to output expression. A Push operator + into stack. A + Copy operand B to output expression. AB + Push operator * into stack (Priority of * is higher than +) AB *+ Copy operand C to output expression. ABC *+ Pop operator * and copy to output expression. ABC* + Pop operator + and copy to output expression. ABC*+

182 Infix to Postfix Transformation
Final algorithm (the most general case): Copy the ith operand to output expression. Push the ith operator into stack. Copy the next (i+1st) operand to output expression. If priority of the next operator is higher than priority of the ith operator then push it into stack, otherwise pop the ith operator, copy it to output expression and then push the next operator into stack. Repeat the previous steps until the last operand will be copied to output expression. Pop the operators reminded and copy them to output expression.

183 Infix to Postfix Transformation
Priorities: 2: * / 1: + - 0: (

184

185

186 Backtracking Backtracking is a method to find a proper path to some certain goal, from a number of the ones. This method is widely used in decision analysis, expert systems and computer gaming. Goal seeking is a typical backtracking algorithm of finding the unique path to a desired goal.

187 Backtracking

188

189 Stacks and Subroutines
All the parameters are transferred from (to) a calling program to (from) a subroutine through a stack All the necessary system data (the content of processor registers, the content of the processor status word (PSW), the returning address, etc.) must also be pushed in the stack before a subroutine will be called

190

191 Stacks and Subroutines
A stack frame is a subspace within the stack that is assigned for a particular subroutine. The stack frame contains the following elements: 1) the parameters to be processed by the called algorithm; 2) the system data (register and PSW content) in the calling algorithm; 3) the return address in the calling algorithm; 4) the expression that is to receive the return value (if any, in the case of function-subroutine).

192 Parameter Passing It is also necessary to take into account that general purpose processor registers can be used by the calling program and by the subroutine separately. This means that their contents must be preserved before calling the subroutine.

193 Stack Frame A private work space for the subroutine inside the stack, created at the time the subroutine is entered and freed up when the subroutine returns control to the calling program is called a stack frame. To save the memory space and to simplify access to data used by the subroutine, the local memory variables used by the subroutine can also be placed in the stack frame. The frame pointer (FP) is a pointer register which is used for access to the parameters passed to the subroutine and to the local memory variables used by the subroutine.

194 Problem-Example 1 Suppose we need to allocate the subroutine in the memory. This subroutine will use registers R0, R1,, and 4 parameters PAR1, PAR2, PAR3, and PAR4 that will be passed from the calling program

195 Problem-Example 1 Stack Comment PAR1 PAR2 PAR3 PAR4 (R0) (R1)
RETURN ADDRESS Paramenter PAR1 Paramenter PAR2 Paramenter PAR3 Paramenter PAR4 The old contents of R0 The old contents of R1 Address for return to the calling program

196 Problem-Example 2 Suppose we need to allocate two subroutines in the memory: SUB1 and SUB2. SUB1 will use register R0, and parameter A passed from the calling program SUB2 will be called from SUB1 and will use registers R0, R1, and parameters B,C,D passed from SUB1

197 Problem-Example 2 Stack Comment D C B (R0) (R1) SUB 2 RETURN ADDR. A
Paramenter D Parameter C Parameter B R0 from SUB1 The old contents of R1 Return address for SUB2 Parameter A The old contents of R0 Return address for SUB1

198 Recursive function (subroutine) and stack

199 Factorial (3): Decomposition and solution

200

201

202 Homework P.140 Exercises 3 a, b, c (only postfix, try both manual and algorithmic methods) P.140 Exercise 4 a, b P. 140 Exercise 5

203 List Chapter 5 Objectives Upon completion you will be able to:
Explain the design, use, and operation of a linear list Implement a linear list using a linked list structure Understand the operation of the linear list ADT Write application programs using the linear list ADT Design and implement different link-list structures Data Structures: A Pseudocode Approach with C 203

204 5-1 Basic Operations Insertion Deletion Retrieval Traversal
We begin with a discussion of the basic list operations. Each operation is developed using before and after figures to show the changes. Insertion Deletion Retrieval Traversal Data Structures: A Pseudocode Approach with C 204

205 Data Structures: A Pseudocode Approach with C
205

206 Data Structures: A Pseudocode Approach with C
206

207 Data Structures: A Pseudocode Approach with C
207

208 Data Structures: A Pseudocode Approach with C
208

209 Data Structures: A Pseudocode Approach with C
209

210 Data Structures: A Pseudocode Approach with C
210

211 Data Structures: A Pseudocode Approach with C
211

212 Data Structures: A Pseudocode Approach with C
212

213 Data Structures: A Pseudocode Approach with C
213

214 Data Structures: A Pseudocode Approach with C
214

215 Data Structures: A Pseudocode Approach with C
215

216 Data Structures: A Pseudocode Approach with C
216

217 Data Structures: A Pseudocode Approach with C
217

218 Data Structures: A Pseudocode Approach with C
218

219 Data Structures: A Pseudocode Approach with C
219

220 List Search A list search is used to locate data in a list
To insert data, we need to know the logical predecessor to the new data. To delete data, we need to find the node to be deleted and identify its logical predecessor. To retrieve data from a list, we need to search the list and find the data. Data Structures: A Pseudocode Approach with C 220

221 List Search We must use a sequential search because there is no physical relationship among the nodes. The classic sequential search returns the location of an element when it is found and the address of the last element when it is not found. Because the list is ordered, we need to return the location of the element when it is found and the location where it should be placed when it is not found. Data Structures: A Pseudocode Approach with C 221

222 List Search Given a target key, the ordered list search attempts to locate the requested node in the list. To search a list on a key, we need a key field. For simple lists the key and the data can be the same field. If a node in the list matches the target value, the search returns true; if there are no key matches, it returns false. Data Structures: A Pseudocode Approach with C 222

223 Data Structures: A Pseudocode Approach with C
223

224 Data Structures: A Pseudocode Approach with C
224

225 Traversals Algorithms that traverse a list start at the first node and examine each node in succession until the last node has been processed. Traversal logic is used by such types of algorithms as changing a value in each node, printing a list, summing a list, calculating the average, etc. To traverse a list, we need a walking pointer that moves from node to node Data Structures: A Pseudocode Approach with C 225

226 Doubly Linked List A doubly linked list is a linked list structure in which each node has a pointer to both its successor and its predecessor. Data Structures: A Pseudocode Approach with C 226

227 Data Structures: A Pseudocode Approach with C
227

228 ADT Structure There are three pieces of metadata in the head structure: a count, a position pointer for traversals, and a rear pointer: Data Structures: A Pseudocode Approach with C 228

229 Circularly Linked List
In a circularly linked list, the last node’s link points to the first node of the list. Circularly linked lists are primarily used in lists that allow access to nodes in the middle of the list without starting at the beginning. Data Structures: A Pseudocode Approach with C 229

230 Data Structures: A Pseudocode Approach with C
230

231 Homework Chapter 5 Exercises 1-3, pp. 249-250 Problem 10, p. 251
Data Structures: A Pseudocode Approach with C 231

232 Binary Search Trees Chapter 7 Objectives
Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree ADT Write application programs using the binary search tree ADT Design and implement a list using a BST Design and implement threaded trees Data Structures: A Pseudocode Approach with C, Second Edition 232

233 A Binary Search Tree is a binary tree with the following properties:
All items in the left subtree are less than the root. All items in the right subtree are greater or equal to the root. Each subtree is itself a binary search tree. Data Structures: A Pseudocode Approach with C, Second Edition 233

234 Basic Property In a binary search tree,
the left subtree contains key values less than the root the right subtree contains key values greater than or equal to the root. Data Structures: A Pseudocode Approach with C, Second Edition 234

235 7-1 Basic Concepts Binary search trees provide an excellent structure for searching a list and at the same time for inserting and deleting data into the list. Data Structures: A Pseudocode Approach with C, Second Edition 235

236 Data Structures: A Pseudocode Approach with C, Second Edition
236

237 (a), (b) - complete and balanced trees;
(d) – nearly complete and balanced tree; (c), (e) – neither complete nor balanced trees Data Structures: A Pseudocode Approach with C, Second Edition 237

238 Data Structures: A Pseudocode Approach with C, Second Edition
238

239 7-2 BST Operations Traversals Searches Insertion Deletion
We discuss four basic BST operations: traversal, search, insert, and delete; and develop algorithms for searches, insertion, and deletion. Traversals Searches Insertion Deletion Data Structures: A Pseudocode Approach with C, Second Edition 239

240 Data Structures: A Pseudocode Approach with C, Second Edition
240

241 Data Structures: A Pseudocode Approach with C, Second Edition
241

242 Preorder Traversal Data Structures: A Pseudocode Approach with C, Second Edition 242

243 Postorder Traversal Data Structures: A Pseudocode Approach with C, Second Edition 243

244 Inorder traversal of a binary search tree produces a sequenced list
Inorder traversal of a binary search tree produces a sequenced list Data Structures: A Pseudocode Approach with C, Second Edition 244

245 Right-Node-Left Traversal
Right-node-left traversal of a binary search tree produces a descending sequence Data Structures: A Pseudocode Approach with C, Second Edition 245

246 Three BST search algorithms:
Find the smallest node Find the largest node Find a requested node Data Structures: A Pseudocode Approach with C, Second Edition 246

247 Data Structures: A Pseudocode Approach with C, Second Edition
247

248 Data Structures: A Pseudocode Approach with C, Second Edition
248

249 Data Structures: A Pseudocode Approach with C, Second Edition
249

250 Data Structures: A Pseudocode Approach with C, Second Edition
250

251 Data Structures: A Pseudocode Approach with C, Second Edition
251

252 Data Structures: A Pseudocode Approach with C, Second Edition
252

253 BST Insertion To insert data all we need to do is follow the branches to an empty subtree and then insert the new node. In other words, all inserts take place at a leaf or at a leaflike node – a node that has only one null subtree. Data Structures: A Pseudocode Approach with C, Second Edition 253

254 Data Structures: A Pseudocode Approach with C, Second Edition
254

255 Data Structures: A Pseudocode Approach with C, Second Edition
255

256 Data Structures: A Pseudocode Approach with C, Second Edition
256

257 30 30 30 30 Data Structures: A Pseudocode Approach with C, Second Edition 257

258 Deletion There are the following possible cases when we delete a node:
The node to be deleted has no children. In this case, all we need to do is delete the node. The node to be deleted has only a right subtree. We delete the node and attach the right subtree to the deleted node’s parent. The node to be deleted has only a left subtree. We delete the node and attach the left subtree to the deleted node’s parent. The node to be deleted has two subtrees. It is possible to delete a node from the middle of a tree, but the result tends to create very unbalanced trees. Data Structures: A Pseudocode Approach with C, Second Edition 258

259 Deletion from the middle of a tree
Rather than simply delete the node, we try to maintain the existing structure as much as possible by finding data to take the place of the deleted data. This can be done in one of two ways. Data Structures: A Pseudocode Approach with C, Second Edition 259

260 Deletion from the middle of a tree
We can find the largest node in the deleted node’s left subtree and move its data to replace the deleted node’s data. We can find the smallest node on the deleted node’s right subtree and move its data to replace the deleted node’s data. Either of these moves preserves the integrity of the binary search tree. Data Structures: A Pseudocode Approach with C, Second Edition 260

261 Data Structures: A Pseudocode Approach with C, Second Edition
261

262 (continued) Data Structures: A Pseudocode Approach with C, Second Edition 262

263 27 27 27 27 Data Structures: A Pseudocode Approach with C, Second Edition 263

264 7-3 Binary Search Tree ADT
We begin this section with a discussion of the BST data structure and write the header file for the ADT. We then develop 14 programs that we include in the ADT. Data Structure Algorithms Data Structures: A Pseudocode Approach with C, Second Edition 264

265 Data Structures: A Pseudocode Approach with C, Second Edition
265

266 Data Structures: A Pseudocode Approach with C, Second Edition
266

267 Homework: Preparation for the final test
Chapter 6 (pp ) Chapter 7 (Sections 7.1; 7.2) p. 292: ex. 1; p. 293: ex. 6, ex. 12 P. 337: ex. 3, ex. 4, ex.6, ex. 7 P. 338: ex. 13, ex. 14 267


Download ppt "Data Structures 1."

Similar presentations


Ads by Google