CMP216 - Fundamentals of A Data Structure
CMP216 - Fundamentals of A Data Structure
COURSE
GUIDE
CIT 216
FUNDAMENTALS OF DATA STRUCTURES
1 1
1 1
1
CIT 216 CIT 216 FUNDAMENTALS OF DATA STRUCTURES
Lagos Office
14/16 Ahmadu Bello Way
Victoria Island, Lagos
e-mail: [email protected]
URL: www.nou.edu.ng
ISBN: 978-058-031-X
2 2
2 2
2
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
CONTENTS PAGE
Introduction……………………………………………………… 1
What this Course Will Help You Do………………….………… 1
Course Aims……………………………………..………………. 1
Course Objectives…………………………..……………………. 1
Working through this Course…………………….……………… 2
Course Materials………………………………………..……….. 2
Online Materials………………………………………………… 2
Equipment………………………………………………….……. 2
Study Units ……………………………………………………… 3
Assessment………………………………………………….…… 5
Course Overview………………………………………………... 5
How to Get the Most from this Course……………………..……. 5
Facilitators/Tutors and Tutorials………………………………… 6
Summary………………………………………………….……… 7
Introduction
The overall aims and objectives of this course provide guidance on what
you should be achieving in the course of your studies. Each unit also has
its own unit objectives which state specifically what you should be
achieving in the corresponding unit. To evaluate your progress
continuously, you are expected to refer to the overall course aims and
objectives as well as the corresponding unit objectives upon the
completion of each.
Course Aims
The overall aims and objectives of this course include:
3 3
3 3
3
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
Course Objectives
Upon completion of the course, you should be able to:
Course Materials
4 4
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
Online Materials
Feel free to refer to the websites provided for all the online reference
materials required in this course. The website is designed to integrate
with the print-based course materials. The structure follows the structure
of the units and all the reading and activity numbers are the same in both
media.
Equipment
In order to get the most from this course, it is essential that you make
use of a computer system which has internet access.
Processor
Operating System
Monitor*
19-inch
1024 X 768 resolution
16-bit high color
*Non Standard resolutions (for example, some laptops) are not
supported.
Hardware
Laser Printer
5 5
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
If your system does not meet the recommended specifications, you may
experience considerably slower processing when working in the
application. Systems that exceed the recommended specifications will
provide better handling of database files and faster processing time,
thereby significantly increasing your productivity.
Study Units
Unit 1 Fundamentals
Unit 2 Arrays
Unit 3 The List Data Structure
Unit 4 The Stack Data Structure
Unit 5 The Queue Data Structure
Unit 1 Hashing
Unit 2 Trees
Unit 3 Search Trees
Unit 4 Garbage Collection
Unit 5 Memory Allocation
Unit 1 Classes
Unit 2 Objects
77 77
7
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
Module 5 Algorithms
Modules one and two describe the foundational data structures and their
underlying principles. Modules three and four define the basic concepts
of an object-oriented programming language (Java). It uses java as a
programming language to implement a variety of data structures, while
modules five and six discuss the analysis of algorithms and algorithm
techniques.
Assessment
The examination aims at testing your ability to apply the knowledge you
have gain throughout the course, rather than your ability to memorise
the materials. In preparing for the examination, it is essential that you
receive the activities and Tutor-marked assignments you have completed
in each unit. The other 50% will account for all the TMAs at the end of
each unit.
88 88
8
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
Course Overview
This section proposes the number of weeks that you are expected to
spend on the three modules comprising 30 units and the assignments
that follow each of the units.
Your tutor will mark and comment on your assignments, keep a close
watch on your progress and on any difficulties you might encounter and
provide assistance to you during the course. You must mail your TMAs
to your tutor well before the due date (at least two working days are
required). They will be marked by your tutor and returned to you as
soon as possible.
9
9
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
i. You do not understand any part of the study units or the assigned
readings.
ii. You have difficulty with the TMAs.
iii. You have a question or problem with your tutor’s comments on
an assignment or with the grading of an assignment.
You should try your best to attend tutorials, since it is the only
opportunity to have an interaction with your tutor and to ask questions
which are answered instantly. You can raise any problem encountered in
the course of your study. To gain maximum benefit from the course
tutorials, you are advised to prepare a list of questions before attending
the tutorial. You will learn a lot from participating in discussions
actively.
Summary
We hope that you will find the course enlightening and that you will
find it both interesting and useful. In the longer term, we hope you
will get acquainted with the National Open University of Nigeria
and we wish you every success in your future.
1
0
1
CIT 216 FUNDAMENTALS OF DATA STRUCTURES
CONTENTS PAGE
Module 1 Foundational Data Structures………………… 1
Unit 1 Fundamentals………………………….…………. 1
Unit 2 Arrays………………………………….…………. 7
Unit 3 The List Data Structure………………..………….. 12
Unit 4 The Stack Data Structure………………..………… 18
Unit 5 The Queue Data Structure………………..……….. 24
Module 2 Foundational Data Structures…………………... 32
Unit 1 Hashing………………………………………….... 32
Unit 2 Trees………………………….………….……….. 43
Unit 3 Search Trees………………………….………….. 54
Unit 4 Garbage Collection………………………...……… 70
Unit 5 Memory Allocation……………………..………… 80
Module 3 Introduction to Java Programming…………..… 85
Unit 1 Object-Oriented Programming Concepts………… 85
Unit 2 Variables…………………………………………. 95
Unit 3 Operators…………………………………………. 99
Unit 4 Expressions, Statements and Blocks………….…… 107
Unit 5 Control Flow Statements…………………………. 112
Module 4 Introduction to Java Programming……………. 122
Unit 1 Classes……………………………………….……. 122
Unit 2 Objects ……………………………………….…… 129
Unit 3 Interfaces and Inheritances……………………….. 140
Unit 4 Numbers and Strings……………………….……… 150
Unit 5 Generics………………………………….………… 159
Module 5 Algorithms…………………………….………….. 168
Unit 1 Introduction to Algorithms…………….……….….. 168
Unit 2 Vectors and Matrices………………..…………….. 174
Unit 3 Greedy Algorithms………………………..………. 179
Unit 4 Divide-and-Conquer Algorithm………………..…. 182
Unit 5 Dynamic Programming Algorithm……………..…. 185
Module 6 Algorithms………………………….…………….. 189
Unit 1 Graph Algorithm……………………………..…….. 189
Unit 2 Sorting…………………………………………..….. 193
Unit 3 Bubble Sort……………………………………….... 197
Unit 4 Insertion Sort……………………….……………… 201
Unit 5 Selection Sort…………………………….……….. 205
Unit 6 Merge Sorting……………………………………... 210
xiii
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Unit 1 Fundamentals
Unit 2 Arrays
Unit 3 The List Data Structure
Unit 4 The Stack Data Structure
Unit 5 The Queue Data Structure
UNIT 1 FUNDAMENTALS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Data Type
3.2 Data Type Classification
3.2.1 Examples of Data Type
3.3 Abstract Data Type
3.3.1 Examples of Abstract Data Type
3.4 What is a Data Structure?
3.5 Classification of Data Structures
3.5.1 Linear Data Structure
3.5.2 Non-Linear Data Structure
3.6 Data Structures and Programmes
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit introduces some basic concepts that the student needs to be
familiar with before attempting to develop any software. It describes
data type and data structures, explaining the operations that may be
performed on them. The unit introduces you to the fundamental notions
of data structures, thus guiding you through and facilitating your
understanding of the subsequent units.
1 1
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
2.0 OBJECTIVES
Some data items may be used singly whilst others may be combined
together and arranged to form other data items. The former are classified
as ‘simple data types’ whereas the latter are classified as ‘data
structures’. However, the following classification is appropriate for
study at this level .The simple data types are classified as follows:
a. Character
b. Numeric integer
c. Numeric real
d. Boolean (logical).
2 2
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3 3
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4 4
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about the classification of abstract data
type, commonly referred to as ADT. You have also been able to
understand the meaning of some notions such as; data type, abstract data
type and data structures. Finally, you have been able to appreciate the
significance of data structures in developing high-quality programmes.
5.0 SUMMARY
What you have learned borders on the basic notions of data structures.
The subsequent units shall build upon these fundamentals.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme, (2nd
Edition). New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL, (2nd Edition), New Jersey: Prentice Hall,
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
5 5
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
6 6
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 2 ARRAYS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Arrays
3.2 Arrays and Programming
3.3 Declaration of Arrays
3.4 Multi-Dimensional Arrays
3.5 Classification of Arrays
3.6 Application of Arrays
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will learn about arrays, their declaration, dimensionality
and applications. You will also learn how to distinguish between static
and dynamic arrays.
2.0 OBJECTIVES
3.1 Arrays
7 7
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
int[] anArray;
anArray = new int[10];
The size of an array can be found using the length attribute. For
example:
int len = anArray.length
Before any array is used in the computer, some memory locations have
to be created for storage of the elements. This is often done by using the
DIM instruction of BASIC programming language or DIMENSION
instruction of FORTRAN programming language. For example, the
instruction:
will create 45 memory locations for storage of the elements of the array
called LAGOS.
In most programming languages, each element has the same data type
and the array occupies a contiguous area of storage. Most programming
languages have a built-in array data type. Some programming languages
support array programming which generalises operations and functions
to work transparently over arrays as they do with scalars, instead of
requiring looping over array members.
8 8
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
int age1;
int age2;
int age3;
int age[6];This creates a six element array; the elements can be accessed
as age[0] through age[5] in C.
A two-dimensional array (in which the elements are arranged into rows
and columns) declared by say DIM X(3,4) can be stored as linear arrays
in the computer memory by determining the product of the subscripts.
The above can thus be expressed as DIM X (3 * 4) or DIM X (12).
9 9
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Arrays can be classified as static arrays (i.e. whose size cannot change
once their storage has been allocated), or dynamic arrays, which can be
resized.
4.0 CONCLUSION
In this unit, you have learned about the arrays and their dimensionality.
You have also been able to understand the meaning of some notions
such as; array name, element and array declaration. Finally, you have
been able to distinguish between the static and dynamic arrays as well as
understand the applications of arrays.
5.0 SUMMARY
10 10
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
11 11
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is a List?
3.2 Elements of a List
3.3 Operation
3.4 List Implementation
3.4.1 Array List
3.4.2 Linked List
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
What you will learn in this unit borders on Lists, their operations and
implementations. Typical examples are given to facilitate the student’s
understanding of these features.
2.0 OBJECTIVES
describe a List
identify the elements of a List
explain the operations and implementations of Lists.
Lists differ from the stacks and queues data structures in that additions
and removals can be made at any position in the list.
12 12
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.2 Operations
Add
e.g. Add(1,X,L) adds the value X to list L at position 1 (the start of the
list is position 0), shifting subsequent elements up L
A B C
13 13
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
A X B C
Fig. 1.2: List after adding value
Set
L
A X Z C
Remove
L
A X Z C
L
A X C
Get
IndexOf
e.g. IndexOf(X,L) returns the index of the node with value X, i.e. 1
1. Array List
2. Linked List
14 14
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
This implementation stores the list in an array. The Array List has the
following properties:
2. Given any index, the element with that index can be accessed in
constant time – i.e. the time to access does not depend on the size
of the list.
3. To add an element at the end of the list, the time taken does not
depend on the size of the list. However, the time taken to add an
element at any other point in the list does depend on the size of
the list, as all subsequent elements must be shifted up. Additions
near the start of the list take longer than additions near the middle
or end.
4. When an element is removed, subsequent elements must be
shifted down, so removals near the start of the list take longer
than removals near the middle or end.
There are many variations on the Linked List data structure, including:
15 15
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
A singly linked list is a data structure in which the data items are
chained (linked) in one direction. Figure 1 shows an example of a singly
linked list.
In a circularly linked list, the tail of the list always points to the head of
the list.
16 16
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit you have learned about Lists. You have also been able to
identify the elements of a List. You should also have learned about
operations and implementations of lists.
5.0 SUMMARY
What you have learned in this unit concerns the Lists, their operations
and implementations. In the next unit, you shall learn about another
linear data structure, known as Queues.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
17 17
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Stack Data Structure
3.2 Application of Stacks
3.3 Operations on a Stack
3.4 Stack Storage Modes
3.4.1 Static Data Structures
3.4.2 Dynamic Data Structures
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, we will look at an abstract data structure – the Stack Data
Structure.
This structure stores and accesses data in different ways, which are
useful in different applications. In all cases, the stack data structure
follows the principle of data abstraction (the data representation can be
inspected and updated only by the abstract data type’s operations). Also,
the algorithms used to implement the operations do not depend on the
type of data to be stored.
2.0 OBJECTIVES
18 18
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
19 19
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
these algorithms use stacks to remember the search nodes that have been
noticed but not explored yet.
20 20
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Figure 1.2 shows the insertion of three data X, Y and Z to a stack and
the removal of two data, Z and Y, from the stack.
To X To Y To Z To Y To X
p p X p Y p X p
X
Stack
Fig. 1. 2: Insertion and removal of data from stack
X
S
Fig 1.4: Stack after adding the value X
21 21
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Pop
e.g. Pop(S) removes the TOP node and returns its value
S
Fig. 1.5: Stack after removing the top node
4.0 CONCLUSION
In this unit, you have learned about the stack data structure. You have
also been able to understand the basic operations on a stack. You should
also have learned about applications of stacks in computing.
22 22
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
What you have learned in this unit concerns the stack data structure,
their operations and applications. In the next unit, you shall learn about
another linear data structure, known as Queues.
Applying the LIFO principle to the third stack S, what would be the
state of the stack S, after the operation S. POP ( ) is executed? Illustrate
this with a simple diagram.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
23 23
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Queue Data Structure
3.2 Application of Queues
3.3 Operations on a Queue
3.3.1 Other Queue Operations
3.4 Storing a Queue in a Static Data Structure
3.5 Storing a Queue in a Dynamic Data Structure
3.5.1 Adding a Node
3.5.2 Removing a Node
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, the student will gain knowledge of the queue data structure
as well as its applications and operations. Typical examples are given to
facilitate your understanding of these concepts.
2.0 OBJECTIVES
The queue data structure is characterised by the fact that additions are
made at the end, or tail, of the queue while removals are made from the
front, or head of the queue. For this reason, a queue is referred to as a
FIFO structure (First-In First-Out). Figure 1.0 shows a queue of part of
English alphabets.
Insertion Deletion
24 24
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Creates the structure – i.e. ensures that the structure exists but contains
no elements.
Add
25 25
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Remove
e.g. Remove(Q) removes the head node and returns its value
26 26
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5:
27 27
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The new node is to be added at the tail of the queue. The reference
Queue.Tail should point to the new node, and the NextNode reference
of the node previously at the tail of the queue should point to the
DataItem of the new node.
28 28
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
29 29
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about the queue data structure. Queue
applications and operations were equally considered. You should also
have learned about the queue storage in static and dynamic data
structures.
5.0 SUMMARY
What you have learned in this unit concerns queues, their operations and
applications. The units that follow shall build upon issues discussed in
this unit.
Taking up again the example given in figure 1.4 above, show the state of
the queue after the following operations:
Add (E,Q)
Remove (Q)
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
30 30
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
31 31
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Unit 1 Hashing
Unit 2 Trees
Unit 3 Search Trees
Unit 4 Garbage Collection and Other Heap
Unit 5 Memory Allocation
UNIT 1 HASHING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Hashing-The Basic Idea
3.2 Hash Keys and Functions
3.3 Hash Function Implementation
3.4 What is a Hash Table?
3.4.1 Abstract Hash Tables
3.5 Separate Chaining
3.6 Applications
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, we will examine the basic idea of hashing. Hash keys and
functions are equally described, giving the basic implementation of hash
functions. We then define hash tables and give their applications.
2.0 OBJECTIVES
32 32
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Ideally we would build a data structure for which both the insertion and
find operations are O (1) in the worst case. However, this kind of
performance can only be achieved with complete a priori knowledge.
We need to know beforehand specifically which items are to be inserted
into the container. Unfortunately, we do not have this information in the
general case. So, if we cannot guarantee O (1) performance in the worst
case, then we make it our design objective to achieve O(1) performance
in the average case.
Clearly, neither the ordered list nor the sorted list meets our performance
objectives. The essential problem is that a search, either linear or binary,
is always necessary. In the ordered list, the find operation uses a linear
search to locate the item. In the sorted list, a binary search can be used
to locate the item because the data is sorted. However, in order to keep
the data sorted, insertion becomes O(n).
Example
33 33
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
x h(x)
"ett" 1
"två" 2
"tre" 3
"fyra" 4
"fem" 5
"sex" 6
"sju" 7
"åtta" 8
"nio" 9
"tio" 10
"elva" 11
"tolv" 12
In the general case, we expect the size of the set of keys, |K|, to be
relatively large or even unbounded. For example, if the keys are 32-bit
integers, then . Similarly, if the keys are arbitrary character
strings of arbitrary length, then |K| is unbounded.
34 34
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
On the other hand, we also expect the actual number of items stored in
the container to be significantly less than |K|. That is, if n is the number
of items actually stored in the container, then . Therefore, it
seems prudent to use an array of size M, where M is as least as great at
the maximum number of items to be stored in the container.
35 35
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
36 36
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
37 37
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Figure 1.1, shows a hash table that uses separate chaining to resolve
collisions. The hash table is implemented as an array of linked lists. To
insert an item into the table, it is appended to one of the linked lists. The
linked list to which it is appended is determined by hashing that item.
38 38
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Figure 1.1 illustrates an example in which there are M=16 linked lists.
The twelve character strings "ett"-"tolv" have been inserted into
the table using the hashed values and in the order given in Table 1.1.
Notice that in this example, since M=16, the linked list is selected by the
least significant four bits of the hashed value given in Table 1.0. In
effect, it is only the last letter of a string which determines the linked list
in which that string appears.
3.6 Applications
39 39
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The static inner class Counter extends the class Int defined in
Section . In addition to the functionality inherited from the base class,
the Counter class adds the method increment which increases the
value by one.
The wordCounter method does the actual work of counting the words
in the input file. The local variable table refers to a
ChainedHashTable that is used to keep track of the words and
counts. The objects which are put into the hash table are all instances of
the class Association. Each association has as its key a String
class instance, and as its value a Counter class instance.
40 40
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The wordCounter method reads words from the input stream one at a
time. As each word is read, a find operation is done on the hash table
to determine if there is already an association for the given key. If none
is found, a new association is created and inserted into the hash table.
The given word is used as the key of the new association and the value
is a counter which is initialised to one. On the other hand, if there is
already an association for the given word in the hash table, the
corresponding counter is incremented. When the wordCounter
method reaches the end of the input stream, it simply prints the hash
table on the given output stream.
4.0 CONCLUSION
In this unit, you have learned about hashing, hash keys and functions.
You have also been able to understand what hash tables are and how to
implement hash functions. Finally, you have been able to appreciate the
applications of hash tables.
5.0 SUMMARY
What you have learned borders on the basic notions of hashing, hash
functions and hash tables and their applications.
41 41
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
42 42
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 2 TREES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Trees
3.2 Tree- Basics
3.3 Binary Trees
3.4 Tree Traversals
3.4.1 Preorder Traversal
3.4.2 Postorder Traversal
3.4.3 Inorder Traversal
3.5 Implementing Trees
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
3.1 Trees
43 43
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.2
Tree-
Basics
44 44
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
It follows from the definition that the minimal tree is a tree comprising a
single root node. For example is such a tree. When there is
more than one node, the remaining nodes are partitioned into subtrees.
For example, the is a tree which comprises of the root
node, B, and the subtree . Finally, the following is also a tree
45 45
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
46 46
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
with respect to this pictorial representation. For example, when we move from
a root to a subtree, we will say that we are moving down the tree. The inverted
pictorial representation of trees is probably due to the way that genealogical
lineal charts are drawn. A lineal chart is a family tree that shows the
descendants of some person. And it is from genealogy that much of the
terminology associated with tree data structures is taken.
Terminology
Definition (Path and Path Length) Given a tree, T, containing the set of
nodes R, a path in T is defined as a non-empty sequence of nodes
For example, consider again the tree shown in Figure 1.1. This tree
contains many different paths. In fact, if you count carefully, you should
find that there are exactly 29 distinct paths in tree . This includes the path
of length zero, ; the path of length one, ; and the path of length
three, .
47 47
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
for which N is two. Since a binary tree is an N-ary tree, all of the results
derived in the preceding section apply to binary trees. However, binary
trees have some interesting characteristics that arise from the restriction
that N is two. For example, there is an interesting relationship between
binary trees and the binary number system. Binary trees are also very
useful for the representation of mathematical expressions involving the
binary operations such as addition and multiplication.
The tree, is called the left subtree of T, and the tree, is called the
right subtree of T.
48 48
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The discussion that follows uses the tree in Figure 1.3 as an example.
The tree shown in the figure is a general tree:
However, we can also consider the tree in Figure 1.3 to be an N-ary tree
(specifically, a binary tree if we assume the existence of empty trees at
the appropriate positions:
49 49
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Preorder traversal gets its name from the fact that it visits the root first.
In the case of a binary tree, the algorithm becomes:
For example, a preorder traversal of the tree visits the nodes in the
following order:
Notice that the preorder traversal visits the nodes of the tree in precisely
the same order in which they are written. A preorder traversal is often
done when it is necessary to print a textual representation of a tree.
50 50
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
An inorder traversal of the tree visits the nodes in the following order:
Programme 1.0 defines the Tree interface. The Tree interface extends
the Container interface defined in Programme 1.0.
51 51
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The Tree interface adds the following methods to those inherited from
the Container interface:
getKey
This method returns the object contained in the root node of a tree.
getSubtree
isEmpty
isLeaf
getDegree
This method returns the degree of the root node of the tree. By
definition, the degree of an external node is zero.
getHeight
This method returns the height of the tree. By definition, the height of an
empty tree is -1.
These methods are like the accept method of the container class (see
Section ). Both of these methods perform a traversal. That is, all the
nodes of the tree are visited systematically. The former takes a
PrePostVisitor and the latter takes a Visitor. When a node is
visited, the appropriate methods of the visitor are applied to that node.
52 52
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about trees. You have also learned about
binary trees and tree traversals. Finally, you have been able to learn how
to implement trees.
5.0 SUMMARY
What you have learned in this unit is focused on trees, the common
types and implementation of trees.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
53 53
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Search Tree-Basics
3.2 Searching a Search Tree
3.2.1 Searching an M-way Tree
3.2.2 Searching a Binary Tree
3.3 Successful Search
3.4 Unsuccessful Search
3.5 AVL Search Trees
3.6 Implementing AVL Trees
3.6.1 Inserting Items into AVL Trees
3.6.2 Removing Items from an AVL Tree
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
54 54
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
a search tree is that the keys do not appear in arbitrary nodes of the tree.
Instead, there is a data ordering criterion which determines where a
given key may appear in the tree in relation to the other keys in that tree.
The subsequent sections present two related types of search trees,
M-way search trees and binary search trees.
The main advantage of a search tree is that the data ordering criterion
ensures that it is not necessary to do a complete tree traversal in order to
locate a given item. Since search trees are defined recursively, it is easy
to define a recursive search method.
Consider the search for a particular item, say x, in an M-way search tree.
The search always begins at the root. If the tree is empty, the search
fails. Otherwise, the keys contained in the root node are examined to
determine if the object of the search is present. If it is, the search
terminates successfully. If it is not, there are three possibilities: Either
the object of the search, x, is less than , in which case subtree is
searched; or x is greater than , in which case subtree is
searched; or there exists an i such that for which
, in which case subtree is searched.
Notice that when x is not found in a given node, only one of the n
subtrees of that node is searched. Therefore, a complete tree traversal is
not required. A successful search begins at the root and traces a
downward path in the tree, which terminates at the node containing the
object of the search. Clearly, the running time of a successful search is
determined by the depth in the tree of object of the search.
When the object of the search is not in the search tree, the search method
described above traces a downward path from the root which terminates
when an empty subtree is encountered. In the worst case, the search path
passes through the deepest leaf node. Therefore, the worst-case running
time for an unsuccessful search is determined by the height of the search
tree.
55 55
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Figure 1.0 shows two binary search trees. The tree is an example of a
particularly bad search tree because it is not really very tree-like at all.
In fact, it is topologically isomorphic with a linear, linked list. In the
worst case, a tree which contains n items has height O(n). Therefore, in
the worst case an unsuccessful search must visit O(n) internal nodes.
1. If h=0, then
and .
2. Otherwise, h>0, in which case both and are both
perfect binary trees of height h-1.
56 56
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.3
Successful
Search
57 57
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
nodes in a given tree. That is, given a binary search tree with n>0 nodes,
The quantity is called the internal path length . The internal path
length of a tree is simply the sum of the depths (levels) of all the internal
nodes in the tree. Clearly, the average depth of an internal node is equal
to the internal path length divided by n, the number of nodes in the tree.
Unfortunately, for any given number of nodes n, there are many
different possible search trees. Furthermore, the internal path lengths of
the various possibilities are not equal. Therefore, to compute the average
depth of a node in a tree with n nodes, we must consider all possible
trees with n nodes. In the absence of any contrary information, we shall
assume that all trees having n nodes are equiprobable and then compute
the average depth of a node in the average tree containing n nodes.
Let I(n) be the average internal path length of a tree containing n nodes.
Consider first the case of n=1. Clearly, there is only one binary tree that
contains one node--the tree of height zero. Therefore, I(1)=0.
In order to determine the average internal path length for a tree with n
nodes, we must compute the average of the internal path lengths of the
trees average over all possible sizes, l, of the (left) subtree,
.
58 58
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
likely. Therefore, the average internal path length for a tree with
nodes is
To solve this recurrence, we consider the case n>1 and then multiply
Equation by n to get
Since this equation is valid for any n>1, by substituting n-1 for n, we
can also write
Thus, we have shown the solution to the recurrence in the equation is the
same as the solution of the recurrence
59 59
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
All successful searches terminate when the object of the search is found.
Therefore, all successful searches terminate at an internal node. In
contrast, all unsuccessful searches terminate at an external node. In
terms of the binary tree shown in Figure 1.0, a successful search
terminates in one of the nodes which are drawn as circles and an
unsuccessful search terminates in one of the boxes.
The preceding analysis shows that the average number of nodes visited
during a successful search depends on the internal path length, which is
simply the sum of the depths of all the internal nodes. Similarly, the
average number of nodes visited during an unsuccessful search depends
on the external path length, which is the sum of the depths of all the
external nodes. Fortunately, there is a simple relationship between the
internal path length and the external path length of a binary tree.
In other words, Theorem says that the difference between the internal
path length and the external path length of a binary tree with n internal
nodes is E-I=2n.
Base Case: Consider a binary tree with one internal node and internal
path length of zero. Such a tree has exactly two empty subtrees
immediately below the root and its external path length is two.
Therefore, the theorem holds for n=1.
60 60
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The difference between the internal path length and the external path
length of is
Since the difference between the internal and external path lengths of
any tree with n internal nodes is 2n, then we can say the same thing
about the average internal and external path lengths average over all
search trees. Therefore, E(n), the average external path length of a
binary search tree is given by
A binary search tree with internal n nodes has n+1 external nodes. Thus,
the average depth of an external node of a binary search tree with n
internal nodes, , is given by
These very nice results are the raison d'être for binary search trees.
What they say is that the average number of nodes visited during either
a successful or an unsuccessful search in the average binary search tree
having n nodes is . We must remember, however, that these
results are premised on the assumption that all possible search trees of n
nodes are equiprobable. It is important to be aware that in practice, this
may not always be the case.
The problem with binary search trees is that while the average running
times for search, insertion, and withdrawal operations are all ,
61 61
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
any one operation is still O(n) in the worst case. This is so because we
cannot say anything in general about the shape of the tree.
For example, consider the two binary search trees shown in Figure .
Both trees contain the same set of keys. The tree, is obtained by
starting with an empty tree and inserting the keys in the following order
The tree is obtained by starting with an empty tree and inserting the
keys in this order
The reason that is better than is that it is the more balanced tree. If
we could ensure that the search trees we construct are balanced, then the
worst-case running time of search, insertion, and withdrawal, could be
made logarithmic rather than linear. But under what conditions is a tree
balanced?
If we say that a binary tree is balanced if the left and right subtrees of
every node have the same height, then the only trees which are balanced
are the perfect binary trees. A perfect binary tree of height h, has exactly
internal nodes. Therefore, it is only possible to create perfect
trees with n nodes for . Clearly, this is an
unsuitable balance condition because it is not possible to create a
balanced tree for every n.
62 62
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Clearly, all perfect binary trees are AVL balanced. What is not so clear
is that heights of all trees that satisfy the AVL balance condition are
logarithmic in the number of internal nodes.
To determine the upper bound, we turn the problem around and ask the
question, what is the minimum number of internal nodes in an AVL
balanced tree of height h?
Let represent an AVL balanced tree of height h which has the smallest
possible number of internal nodes, say . Clearly, must have at least
one subtree of height h-1 and that subtree must be . To remain AVL
balanced, the other subtree can have height h-1 or h-2. Since we want
the smallest number of internal nodes, it must be . Therefore, the
number of internal nodes in is , where .
63 63
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Base Cases
, .
Therefore,
So, we have shown that the AVL balance condition satisfies the first
criterion of a good balance condition--the height of an AVL balanced
tree with n internal nodes is . What remains to be shown is that
the balance condition can be efficiently maintained. To see that it can,
we need to look at an implementation.
64 64
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Programme1.0:
AVLTree fields.
65 65
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Just as in a regular binary search tree, items are inserted into AVL trees
by attaching them to the leaves. To find the correct leaf, we pretend that
the item is already in the tree and follow the path taken by the find
method to determine where the item should go. Assuming that the item
is not already in the tree, the search is unsuccessful and terminates at an
external, empty node. The item to be inserted is placed in that external
node.
Sometimes increasing the height of a subtree does not violate the AVL
balance condition. For example, consider an AVL tree .
Let and be the heights of and , respectively. Since T is an AVL
tree, then . Now, suppose that . Then, if we
insert an item into , its height may increase by one to . The
resulting tree is still AVL balanced since . In fact, this
particular insertion actually makes the tree more balanced! Similarly if
initially, an insertion in either subtree will not result in a
violation of the balance condition at the root of T.
66 66
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
balance.
The method for removing items from an AVL tree is inherited from the
BinarySearchTree class in the same way as AVL insertion. All the
differences are encapsulated in the detachKey and balance
methods. The balance method is discussed above. The detachKey
method is defined in the programme below:
67 67
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about trees. You have also learned about
binary trees and tree traversals. Finally, you have been able to learn how
to implement trees.
5.0 SUMMARY
What you have learned in this unit is focused on trees, the common
types and implementation of trees.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
68 68
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
69 69
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is Garbage?
3.2 Reduce, Reuse, Recycle
3.3 Helping the Garbage Collector
3.4 Reference Counting Garbage Collection
3.5 Mark-and-Sweep Garbage Collection
3.6 The Fragmentation Problem
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
describe garbage
explain garbage collection
describe the mark-and-sweep garbage collection
explain the fragmentation problem.
While Java provides the means to create an object, the language does not
provide the means to destroy an object explicitly. As long as a
programme contains a reference to some object instance, the Java virtual
machine is required to ensure that the object exists. If the Java language
provided the means to destroy objects, it would be possible for a programme
to destroy an object even when a reference to that object still existed. This
situation is unsafe because the programme could attempt later to invoke a
method on the destroyed object, leading to unpredictable results.
70 70
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Languages that support the explicit destruction of objects typically require the
programme to keep track of all the objects it creates and to destroy them
explicitly when they are not longer needed. If a programme somehow
loses track of an object it has created then that object cannot be destroyed.
And if the object is never destroyed, the memory occupied by that object
cannot be used again by the programme.
A programme that loses track of objects before it destroys them suffers from a
memory leak. If we run a programme that has a memory leak for a very long
time, it is quite possible that it will exhaust all the available memory and
eventually fail because no new objects can be created. It would seem that by
disallowing the explicit destruction of objects, a Java programme is
doomed to eventual failure due to memory exhaustion. Indeed, this would be
the case, were it not for the fact that the Java language specification requires
the Java virtual machine to be able to find unreferenced objects and to reclaim
the memory locations allocated to those objects.
An unreferenced object is called garbage and the process of finding all the
unreferenced objects and reclaiming the storage is called garbage collection.
Just as the Java language does not specify precisely how objects are to be
represented in the memory of a virtual machine, the language specification
also does not stipulate how the garbage collection is to be implemented or
when it should be done.
71 71
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
How can we help out the garbage collector? Since the garbage collector
collects only unreferenced objects it is necessary to eliminate all references to
objects which are no longer needed. This is done by assigning the value null
to every variable that refers to an object that is no longer needed.
Consequently, helping the garbage collector requires a programme to do a bit
more work.
72 72
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
This sequence creates a single Integer instance. Both p and q refer to the
same object. Therefore, its reference count should be two.
if (p != q)
{
if (p != null)
--p.refCount;
p = q;
if (p != null)
++p.refCount;
}
As shown in Figure (a), two Integer objects are created, each with a
reference count of one. Now, suppose we assign q to p using the code
sequence given above. Figure (b) shows that after the assignment, both
p and q refer to the same object--its reference count is two. And
73 73
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The costs of using reference counts are twofold: First, every object
requires the special reference count field. Typically, this means an extra
word of storage must be allocated in each object. Second, every time
one reference is assigned to another, the reference counts must be
adjusted as above. This increases significantly the time taken by
assignment statements.
if (p != q)
{
if (p != null)
if (--p.refCount == 0)
heap.release (p);
p = q;
if (p != null)
++p.refCount;
}
Notice that the release method is invoked immediately when the
reference count of an object goes to zero, i.e., when it becomes garbage.
In this way, garbage may be collected incrementally as it is created.
74 74
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In order to distinguish the live objects from garbage, we record the state
of an object in each object. That is, we add a special boolean field to
each object called, say, marked. By default, all objects are unmarked
when they are created. Thus, the marked field is initially false.
An object p and all the objects indirectly accessible from p can be
marked by using the following recursive mark method:
75 75
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
if (!p.marked)
p.marked = true;
for each Object q referenced by p
mark (q);
In its second phase, the mark-and-sweep algorithm scans through all the
objects in the heap, in order to locate all the unmarked objects. The
storage allocated to the unmarked objects is reclaimed during the scan.
At the same time, the marked field on every live object is set back to
false in preparation for the next invocation of the mark-and-sweep
garbage collection algorithm:
void sweep ()
if (p.marked)
p.marked = false
else
heap.release (p);
76 76
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
77 77
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about garbage and garbage collection. You
have also been able to learn about reference counting garbage collection
and mark-and-sweep garbage collection. Finally, you have been able to
understand the fragmentation problem.
5.0 SUMMARY
What you have learned borders on the garbage, garbage collection and
the fragmentation problem.
78 78
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
79 79
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Memory Allocation
3.2 First Fit
3.3 Best Fit
3.4 Fragmentation
3.5 Buddy System
3.6 Suballocators
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
80 80
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Firstfit
Best fit
Buddysystem
Suballocators
In the first fit algorithm, the allocator keeps a list of free blocks (known
as the free list) and, on receiving a request for memory, scans along the
list for the first block that is large enough to satisfy the request. If the
chosen block is significantly larger than that requested, then it is usually
split, and the remainder added to the list as another free block.
The best fit is the allocation policy that always allocates from the
smallest suitable free block. Suitable allocation mechanisms include
sequential fit searching for a perfect fit, first fit on a size-ordered free
block chain, segregated fits, and indexed fits. Many good fit allocators
are also described as bestfit.
In theory, best fit may exhibit bad fragmentation, but in practice, this is
not commonly observed.
3.4 Fragmentation
81 81
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
that size's free list. If the free list for that size is empty, the allocator
splits a block from a larger size and returns one of the pieces, adding the
other to the appropriate free list.
When blocks are recycled, there may be some attempt to merge adjacent
blocks into ones of a larger permitted size (coalescence). To make this
easier, the free lists may be stored in order of address. The main
advantage of the buddy system is that coalescence is cheap because the
"buddy" of any free block can be calculated from its address.
A Fibonacci buddy system might use block sizes 16, 32, 48, 80, 128,
208,... bytes, such that each size is the sum of the two preceding sizes.
When splitting a block from one free list, the two parts get added to the
two preceding free lists.
82 82
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
A buddy system can work very well or very badly, depending on how
the chosen sizes interact with typical requests for memory and what the
3.6 Suballocators
Many applications have one or two sizes of blocks that form the vast
majority of their allocations. One of the most common uses of a
suballocator is to supply the application with objects of one size. This
greatly reduces the problem of external fragmentation. Such a
suballocator can have a very simple allocation policy.
83 83
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about memory allocation. You have also
been able to learn about the first fit, best fit and buddy systems of
memory allocation.
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
84 84
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Objects
3.2 What is a Class?
3.3 Inheritance
3.4 What is an Interface?
3.5 What is a Package?
3.6 Object-Oriented Programming
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
describe an object
explain what a class is
define an Inheritance
explain the term ‘object-oriented programming’.
85 85
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.1 Objects
An object is a software bundle of related state and behaviour. Software
objects are often used to model the real-world objects that you find in
everyday life. This unit explains how state and behaviour are
represented within an object, introduces the concept of data
encapsulation, and explains the benefits of designing your software in
this manner.
Real-world objects share two characteristics: They all have state and
behaviour. Dogs have state (name, colour, breed, hungry) and behaviour
(barking, fetching, wagging tail). Bicycles also have state (current gear,
current pedal cadence, current speed) and behaviour (changing gear,
changing pedal cadence, applying brakes). Identifying the state and
behaviour for real-world objects is a great way to begin thinking in
terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in
your immediate area. For each object that you see, ask yourself two
questions: "What possible states can this object be in?" and "What
possible behaviour can this object put up?” Make sure to write down
your observations. As you do, you'll notice that real-world objects vary
in complexity; your desktop lamp may have only two possible states (on
and off) and two possible behaviours (turn on, turn off), but your
desktop radio might have additional states (on, off, current volume,
current station) and behaviour (turn on, turn off, increase volume,
decrease volume, seek, scan, and tune). You may also notice that some
objects, in turn, will also contain other objects. These real-world
observations all translate into the world of object-oriented programming.
A software object
86 86
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
87 87
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In the real world, you'll often find many individual objects all of the
same kind. There may be thousands of other bicycles in existence, all of
the same make and model. Each bicycle was built from the same set of
blueprints and therefore contains the same components. In
object-oriented terms, we say that your bicycle is an instance of the
class of objects known as bicycles. A class is the blueprint from which
individual objects are created.
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
88 88
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
void printStates() {
System.out.println("cadence:"+cadence+"speed:"+speed+" gear:"+gear);
}
The syntax of the Java programmeming language will look new to you.
The fields cadence, speed, and gear represent the object's state,
and the methods (changeCadence, changeGear, speedUp etc.)
define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main
method. That's because it's not a complete application; it's just the
blueprint for bicycles that might be used in an application. The
responsibility of creating and using new Bicycle objects belongs to
some other class in your application.
class BicycleDemo {
public static void main(String[] args) {
The output of this test prints the ending pedal cadence, speed, and gear
for the two bicycles:
89 89
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.3 Inheritance
90 90
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
This gives MountainBike all the same fields and methods as
Bicycle, yet allows its code to focus exclusively on the features that
make it unique. This makes code for your subclasses easy to read.
However, you must take care to properly document the state and
behaviour that each superclass defines, since that code will not appear in
the source file of each subclass.
interface Bicycle {
}
To implement this interface, the name of your class would change (to
ACMEBicycle, for example), and you'd use the implements
keyword in the class declaration:
}
Implementing an interface allows a class to become more formal about
the behaviour it promises to provide. Interfaces form a contract between
91 91
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
the class and the outside world, and this contract is enforced at build
3.5 WhatisaPackage?
92 92
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
the little widgets on your computer desktop (such as buttons and scroll
bars).
The first step in OOP is to identify all the objects you want to
manipulate and how they relate to each other, an exercise often known
as data modeling. Once you've identified an object, you generalise it as a
class of objects (think of Plato's concept of the "ideal" chair that stands
for all chairs) and define the kind of data it contains and any logic
sequences that can manipulate it. Each distinct logic sequence is known
as a method. A real instance of a class is called (no surprise here) an
"object" or, in some environments, an "instance of a class." The object
or class instance is what you run in the computer. Its methods provide
computer instructions and the class object characteristics provide
relevant data. You communicate with objects - and they communicate
with each other - with well-defined interfaces called messages.
4.0 CONCLUSION
93 93
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Define a class.
What is an inheritance?
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
94 94
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 2 VARIABLES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Basics
3.2 Java Programming Variables
3.3 Naming Conventions
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will learn about variables and their naming conventions.
2.0 OBJECTIVES
define a variable
describe types of java programming variables
explain the naming conventions of variables.
3.1 Basics
95 95
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In the Java programming language, the terms "field" and "variable" are
both used; this is a common source of confusion among new developers,
since both often seem to refer to the same thing.
96 96
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Every programming language has its own set of rules and conventions
for the kinds of names that you're allowed to use, and the Java
programming language is no different. The rules and conventions for
naming your variables can be summarised as follows:
4.0 CONCLUSION
97 97
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
What you have learned in this unit is based on variables and the
conventions for naming them.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
98 98
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 3 OPERATORS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Operators
3.2 The Simple Assignment Operators
3.3 The Arithmetic Operators
3.4 The Unary Operators
3.5 The Equality and Relational Operators
3.6 The Conditional Operators
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
What you will learn in this unit borders on operators. The common types
of operators will equally be discussed.
2.0 OBJECTIVES
3.1 Operators
99 99
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Operator Precedence
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instanceof
Equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
100 100
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
One of the most common operators that you'll encounter is the simple
assignment operator "=". You saw this operator in the Bicycle class; it
assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references, as
discussed in CreatingObjects.
class ArithmeticDemo {
public static void main (String[] args){
101 101
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
System.out.println(result);
}
}
You can also combine the arithmetic operators with the simple
assignment operator to create compound assignments. For example, x
+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings
together, as shown in the following ConcatDemo programme:
class ConcatDemo
{
public static void main(String[] args){
String firstString = "This is";
String secondString = “a concatenated string.”;
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
By the end of this programme, the variable, thirdString, contains
"This is a concatenated string.", which gets printed to standard
output.
The unary operators require only one operand; they perform various
operations such as incrementing/decrementing a value by one, negating
an expression, or inverting the value of a boolean.
102 102
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
}
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
== equal to
!= not equal to
> greater than
>= greater than or equal to
103 103
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
class ComparisonDemo {
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}
Output:
value1 != value2
value1 < value2
value1 <= value2
&& Conditional-AND
|| Conditional-OR
class ConditionalDemo1 {
104 104
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
}
Another conditional operator is?:, which can be thought of as shorthand
for an if-then-else statement (discussed in the Control Flow
Statements section of this lesson). This operator is also known as the
ternary operator because it uses three operands. In the following
example, this operator should be read as: "If someCondition is
class ConditionalDemo2 {
System.out.println(result);
}
}
Because someCondition is true, this programme prints "1" to the
screen. Use the?: operator instead of an if-then-else statement if
it makes your code more readable; for example, when the expressions
are compact and without side-effects (such as assignments).
4.0 CONCLUSION
In this unit you have learned about operators. You have also been able to
identify the common types of operators.
5.0 SUMMARY
What you have learned in this unit concerns operators and the common
types.
105 105
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
106 106
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
1.0 INTRODUCTION
Now that you understand variables and operators, it's time to learn about
expressions, statements, and blocks. Operators may be used in building
expressions, which compute values; expressions are the core
components of statements; statements may be grouped into blocks.
2.0 OBJECTIVES
define an expression
describe statements, giving typical examples of expression statements
discuss the concept of blocks.
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
107 107
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
1*2*3
x + y / 100 // ambiguous
x + y / 100
108 108
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.2 Statements
Statements are roughly equivalent to sentences in natural languages. A
statement forms a complete unit of execution.
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions.
Such statements are called expression statements. Here are some
examples of expression statements.
3.3 Blocks
A block is a group of zero or more statements between balanced braces
and can be used anywhere a single statement is allowed. The following
example, BlockDemo, illustrates the use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
109 109
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
SELF ASSESSMENT EXERCISE 1
4.0 CONCLUSION
In this unit you have learned about the expressions. You have also been
able to distinguish between statements and sentences. You should also
have learned about blocks.
5.0 SUMMARY
What you have learned in this unit concerns expressions, statements and
blocks. In the next unit, you shall learn about control flow statements.
aValue = 8933.234;
aValue++;
System.out.println("Hello World!");
Bicycle myBike = new Bicycle();
110 110
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
111 111
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Control Flow Statements
3.2 The If-Then Statements
3.3 The If-Then-Else Statements
3.4 The Switch Statements
3.5 The While and Do-While Statements
3.6 The For Statements
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, the student will gain knowledge of control flow statements.
The unit describes the decision-making statements (if-then, if-
then-else, switch) and the looping statements (for, while, do-
while), supported by the Java programming language.
2.0 OBJECTIVES
The statements inside your source files are generally executed from top
to bottom, in the order that they appear. Control flow statements,
however, break up the flow of execution by employing decision making,
looping, and branching, enabling your programme to conditionally
execute particular blocks of code.
112 112
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The if-then statement is the most basic of all the control flow
statements. It tells your programme to execute a certain section of code
only if a particular test evaluates to true. For example, the Bicycle
class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. One possible implementation of the
applyBrakes method could be as follows:
void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
In addition, the opening and closing braces are optional, provided that
the "then" clause contains only one statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}
void applyBrakes(){ if
(isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
113 113
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
The following programme, IfElseDemo, assigns a grade based on the
value of a test score: an A for a score of 90% or above, a B for a score of
80% or above, and so on.
class IfElseDemo {
Grade = C
You may have noticed that the value of testscore can satisfy more
than one expression in the compound statement: 76 >= 70 and 76
>= 60. However, once a condition is satisfied, the appropriate
statements are executed (grade = 'C';) and the remaining
conditions are not evaluated.
114 114
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break; case
5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break; case
8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break; case
11: System.out.println("November"); break; case 12:
System.out.println("December"); break; default:
System.out.println("Invalid month.");break;
}
}
}
Of course, you could also implement the same thing with if-then-
else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
115 115
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Another point of interest is the break statement after each case. Each
break statement terminates the enclosing switch statement. Control
flow continues with the first statement following the switch block.
The break statements are necessary because without them, case
statements fall through; that is, without an explicit break, control will
flow sequentially through subsequent case statements. The following
programme, SwitchDemo2, illustrates why it might be useful to have
case statements fall through:
class SwitchDemo2 {
public static void main(String[] args) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
116 116
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Number of Days = 29
Technically, the final break is not required because flow would fall out
of the switch statement anyway. However, we recommend using a
break so that modifying the code is easier and less error-prone. The
default section handles all values that aren't explicitly handled by
one of the case sections.
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
implement an infinite loop using the while statement as follows:
117 117
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement,
which can be expressed as follows:
do {
statement(s)
} while (expression);
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
The initialisation expression initialises the loop; it's executed once, as the
loop begins.
When the termination expression evaluates to false, the loop
terminates.
The increment expression is invoked after each iteration through the
loop; it is perfectly acceptable for this expression to increment or
decrement a value.
118 118
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The following programme, ForDemo, uses the general form of the for
statement to print the numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
The three expressions of the for-loop are optional; an infinite loop can
be created as follows:
119 119
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
In this example, the variable item holds the current value from the
numbers array. The output from this programme is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
4.0 CONCLUSION
The if-then statement is the most basic of all the control flow
statements. It tells your programme to execute a certain section of code
only if a particular test evaluates to true. The if-then-else
statement provides a secondary path of execution when an "if" clause
evaluates to false. Unlike if-then and if-then-else, the
switch statement allows for any number of possible execution paths.
120 120
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
What you have learned in this unit concerns control flow statements.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
121 121
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Unit 1 Classes
Unit 2 Objects
Unit 3 Interfaces and Inheritances
Unit 4 Numbers and Strings
Unit 5 Generics
UNIT 1 CLASSES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Classes
3.2 Declaring Classes
3.3 Declaring Member Variables
3.4 Access Modifiers
3.5 Types
3.6 Variable Names
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
With the knowledge you now have of the basics of the Java
programming language, you can learn to write your own classes. In this
unit, you will find information about defining your own classes,
including declaring member variables, methods, and constructors. This
unit also covers nesting classes within other classes, enumerations, and
annotations
2.0 OBJECTIVES
122 122
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.1 Classes
}
A class declaration for a MountainBike class that is a subclass of
Bicycle might look like this:
public class MountainBike extends Bicycle {
123 123
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
MountainBike inherits all the fields and methods of Bicycle and
adds the field seatHeight, and a method to set it (mountain bikes
have seats that can be moved up and down as the terrain demands).
class MyClass {
}
This is a class declaration. The class body (the area between the braces)
contains all the code that provides for the life cycle of the objects
created from the class: constructors for initialising new objects,
declarations for the fields that provide the state of the class and its objects,
and methods to implement the behaviour of the class and its objects.
124 124
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
You can also add modifiers like public or private at the very beginning
—so you can see that the opening line of a class declaration can become
The Bicycle class uses the following lines of code to define its fields:
125 125
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The fields of Bicycle are named cadence, gear, and speed and
are all of data type integer (int). The public keyword identifies these
fields as public members, accessible by any object that can access the
class.
The first (left-most) modifier used lets you control what other classes have
access to, a member field. For the moment, consider only public and
private. Other access modifiers will be discussed later.
126 126
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.5 Types
All variables must have a type. You can use primitive types such as
int, float, boolean, etc. Or you can use reference types, such as
strings, arrays, or objects.
Note that the same naming rules and conventions are used for method
and class names, except that
4.0 CONCLUSION
127 127
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In this unit, you have learned about classes. You have also been able to
understand how to declare classes and member variables.
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
128 128
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 2 OBJECTS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Objects
3.2 Creating Objects
3.3 Declaring a Variable to Refer to an Object
3.4 Instantiating a Class
3.5 Initialising an Object
3.6 Referencing an Object’s Fields
3.7 Calling an Object’s Methods
3.8 The Garbage Collector
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit covers creating and using objects. You will learn how to
instantiate an object, and, once instantiated, how to use the dot operator
to access the object's instance variables and methods.
2.0 OBJECTIVES
3.1 Objects
129 129
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The following three sections use the above example to describe the life
cycle of an object within a programme. From them, you will learn how
to write code that creates and uses objects in your own programmes.
130 130
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
You will also learn how the system cleans up after an object when its
life has ended.
As you know, a class provides the blueprint for objects; you create an
object from a class. Each of the following statements taken from the
CreateObjectDemo programme creates an object and assigns it to a
variable:
The first line creates an object of the Point class, and the second and
third lines each create an object of the Rectangle class.
Each of these statements has three parts (discussed in detail below):
1. Declaration: The code set in bold are all variable declarations that
associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the
object.
3. Initialisation: The new operator is followed by a call to a
constructor, which initializes the new object.
This notifies the compiler that you will use name to refer to data whose
type is type. With a primitive variable, this declaration also reserves the
proper amount of memory for the variable.
You can also declare a reference variable on its own line. For example:
Point originOne;
131 131
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
pointing to nothing):
The reference returned by the new operator does not have to be assigned
to a variable. It can also be used directly in an expression. For example:
int height = new Rectangle().height;
This statement will be discussed in the next section.
132 132
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Here's the code for the Rectangle class, which contains four
constructors:
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
133 133
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Each constructor lets you provide initial values for the rectangle's size and
width, using both primitive and reference types. If a class has multiple
constructors, they must have different signatures. The Java compiler
differentiates the constructors based on the number and the type of the
arguments. When the Java compiler encounters the following code, it
knows to call the constructor in the Rectangle class that requires a
Point argument followed by two integer arguments:
134 134
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
will see that it creates a new Point object whose x and y values are
initialised to 0:
Rectangle rectTwo = new Rectangle(50, 100);
All classes have at least one constructor. If a class does not explicitly
declare any, the Java compiler automatically provides a no-argument
constructor, called the default constructor. This default constructor calls
the class parent's no-argument constructor, or the Object constructor if
the class has no other parent. If the parent has no constructor (Object
does have one), the compiler will reject the programme.
Using Objects
Object fields are accessed by their name. You must use a name that is
unambiguous.
You may use a simple name for a field within its own class. For
example, we can add a statement within the Rectangle class that
prints the width and height:
Code that is outside the object's class must use an object reference or
expression, followed by the dot (.) operator, followed by a simple field
name, as in:
objectReference.fieldName
135 135
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
objectReference.methodName(argumentList);
or
objectReference.methodName();
136 136
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Some object-oriented languages require that you keep track of all the
objects you create and that you explicitly destroy them when they are no
longer needed. Managing memory explicitly is tedious and error-prone.
The Java platform allows you to create as many objects as you want
(limited, of course, by what your system can handle), and you don't have
to worry about destroying them. The Java runtime environment deletes
objects when it determines that they are no longer being used. This
process is called garbage collection.
137 137
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about objects. You have also learned how to
create and initialise objects. Finally, you have been able to learn the
process of garbage collections.
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
138 138
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
139 139
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Interfaces-Basics
3.2 Interfaces in Java
3.3 Interfaces as APIs
3.4 Interfaces and Multiple Inheritance
3.5 Inheritance
3.6 Definitions
3.7 The Java Platform Class Hierarchy
3.8 What You can Do in a Subclass
3.9 Private Members in a Superclass
3.10 Casting Objects
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit describes the way in which you can derive one class from
another. That is, how a subclass can inherit fields and methods from a
superclass. You will learn that all classes are derived from the Object
class, and how to modify the methods that a subclass inherits from
superclasses. This unit also covers interface-like abstract classes.
2.0 OBJECTIVES
140 140
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
should be able to write their code without any knowledge of how the other
group's code is written. Generally speaking, interfaces are such contracts.
For example, imagine a futuristic society where computer-
controlled robotic cars transport passengers through city streets
without a human operator. Automobile manufacturers write software
(Java, of course) that operates the automobile – stop, start, accelerate, turn
left, and so forth. Another industrial group, electronic
// method signatures
int turn(Direction direction, // An enum with values RIGHT, LEFT
double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double
endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}
141 141
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Note that the method signatures have no braces and are terminated with a
semicolon.
}
In the robotic car example above, it is the automobile manufacturers
who will implement the interface. Chevrolet's implementation will be
substantially different from that of Toyota, of course, but both
manufacturers will adhere to the same interface. The guidance
manufacturers, who are the clients of the interface, will build systems
that use GPS data on a car's location, digital street maps, and traffic data to
drive the car. In so doing, the guidance systems will invoke the interface
methods: turn, change lanes, brake, accelerate, and so forth.
142 142
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In Java, a class can inherit from only one class but it can implement
more than one interface. Therefore, objects can have multiple types: the
type of their own class and the types of all the interfaces that they
implement. This means that if a variable is declared to be a type of an
interface, its value can reference any object that is instantiated from any
class that implements the interface. This is discussed later in this lesson, in
the section titled "Using an Interface as a Type."
3.5 Inheritance
In the preceding units, you have seen inheritance mentioned several times.
In the Java language, classes can be derived from other classes, thereby
inheriting fields and methods from those classes.
3.6 Definitions
Excepting Object, which has no superclass, every class has one and only
one direct superclass (single inheritance). In the absence of any other
explicit superclass, every class is implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that
are derived from classes, and so on, and ultimately derived from the
topmost class, Object. Such a class is said to be descended from all
the classes in the inheritance chain stretching back to Object.
The idea of inheritance is simple but powerful: When you want to create a
new class and there is already a class that includes some of the code
that you want, you can derive your new class from the existing class. In
143 143
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
doing this, you can reuse the fields and methods of the existing class
without having to write (and debug!) them yourself.
A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
An Example of
Inheritance
144 144
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
A class declaration for a MountainBike class that is a subclass of
Bicycle might look like this:
145 145
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
MountainBike inherits all the fields and methods of Bicycle and
adds the field seatHeight and a method to set it. Except for the
constructor, it is as if you had written a new MountainBike class
entirely from scratch, with four fields and five methods. However, you
didn't have to do all the work. This would be especially valuable if the
methods in the Bicycle class were complex and had taken substantial
time to debug.
A subclass inherits all of the public and protected members of its parent,
no matter what package the subclass is in. If the subclass is in the same
package as its parent, it also inherits the package – private members of the
parent. You can use the inherited members as follows: replace them, hide
them, or supplement them with new members:
The inherited fields can be used directly, just like any other field.
You can declare a field in the subclass with the same name as the one
in the superclass, thus hiding it (not recommended).
You can declare new fields in the subclass that are not in the
superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.
You can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
You can declare new methods in the subclass that are not in the
superclass.
You can write a subclass constructor that invokes the constructor of the
146 146
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
A subclass does not inherit the private members of its parent class.
However, if the superclass has public or protected methods for accessing
its private fields, these can also be used by the subclass.
A nested class has access to all the private members of its enclosing
class—both fields and methods. Therefore, a public or protected nested
class inherited by a subclass has indirect access to all of the private
members of the superclass.
3.10 Casting Objects
We have seen that an object is of the data type of the class from which it
was instantiated. For example, if we write
public MountainBike myBike = new MountainBike();
then myBike is of type MountainBike.
Casting shows the use of an object of one type in place of another type,
among the objects permitted by inheritance and implementations. For
example, if we write
147 147
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Note: You can make a logical test as to the type of a particular object
using the instanceof operator. This can save you from a runtime
error owing to an improper cast. For example:
if (obj instanceof MountainBike) {
MountainBike myBike = (MountainBike)obj;
}
Here, the instanceof operator verifies that obj refers to a
MountainBike so that we can make the cast with knowledge that
there will be no runtime exception thrown.
4.0 CONCLUSION
In this unit you have learned about inheritance. You have also learned
about interfaces. Finally, you have been able to learn how to modify
methods.
5.0 SUMMARY
What you have learned in this unit borders on inheritance and interfaces.
148 148
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
149 149
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
1.0 INTRODUCTION
2.0 OBJECTIVES
When working with numbers, most of the time you use the primitive
types in your code. For example:
int i = 500;
float gpa = 3.65;
byte mask = 0xff;
There are, however, reasons to use objects in place of primitives, and the
150 150
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Java platform provides wrapper classes for each of the primitive data
types. These classes "wrap" the primitive in an object. Often, the wrapping
is done by the compiler—if you use a primitive where an object is
expected, the compiler boxes the primitive in its wrapper class for you.
Similarly, if you use a number object when a primitive is expected,
the compiler unboxes the object for you.
Integer x, y;
x = 12; y = 15;
System.out.println(x+y);
When x and y are assigned integer values, the compiler boxes the
integers because x and y are integer objects. In the println()
statement, x and y are unboxed so that they can be added as integers.
All of the numeric wrapper classes are subclasses of the abstract class
Number:
Note: There are four other subclasses of Number that are not discussed
here. BigDecimal and BigInteger are used for high-precision
calculations. AtomicInteger and AtomicLong are used for
multi-threaded applications.
There are three reasons why you might use a Number object rather than
a primitive:
151 151
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The following table lists the instance methods that all the subclasses of
the Number class implement.
Method Description
byte byteValue()
short shortValue()
Converts the value of this Number
int intValue()
long longValue() object to the primitive data type
float floatValue() returned.
double doubleValue()
int compareTo(Byte
anotherByte)
int compareTo(Double
anotherDouble)
int compareTo(Float
anotherFloat) Compares this Number object to
int compareTo(Integer the argument.
anotherInteger)
int compareTo(Long
anotherLong)
int compareTo(Short
anotherShort)
Each Number class contains other methods that are useful for
converting numbers to and from strings and for converting between
number systems. The following table lists these methods in the
Integer class. Methods for the other Number subclasses are similar:
152 152
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
153 153
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
static int
parseInt(String s) Returns an integer (decimal only).
As with any other object, you can create String objects by using the
new keyword and a constructor. The String class has 11 constructors
that allow you to provide the initial value of the string using different
sources, such as an array of characters:
154 154
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
155 155
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
}
You can also use the concat() method with string literals, as in:
156 156
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
You have seen the use of the printf() and format() methods to
print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object
rather than a PrintStream object.
System.out.println(fs);
State three reasons why might use a Number object rather than a
primitive
4.0 CONCLUSION
In this unit you have learned about number classes. You have also
learned how to create and concatenate strings.
5.0 SUMMARY
157 157
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
What you have learned in this unit is focused on numbers and strings.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
158 158
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 5 GENERICS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Generics–Basics
3.2 A Simple Box Class
3.3 Generic Types
3.4 Type Parameter Naming Conventions
3.5 Generic Methods and Constructors
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
In any nontrivial software project, bugs are simply a fact of life. Careful
planning, programming, and testing can help reduce their pervasiveness,
but somehow, somewhere, they'll always find a way to creep into your
code. This becomes especially apparent as new features are introduced
and your code base grows in size and complexity.
159 159
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
and fix it, right then and there. Runtime bugs, however, can be much
more problematic; they don't always surface immediately, and when
they do, it may be at a point in time that's far removed from the actual
cause of the problem.
integerBox.add(new Integer(10));
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
160 160
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
}
161 161
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
at BoxDemo2.main(BoxDemo2.java:6)
If the Box class had been designed with generics in mind, this mistake
would have been caught by the compiler, instead of crashing the
application at runtime.
Let's update our Box class to use generics. We'll first create a generic
type declaration by changing the code "public class Box" to
"public class Box<T>"; this introduces one type variable, named
T, that can be used anywhere inside the class. This same technique can
be applied to interfaces as well. There's nothing particularly complex
about this concept. In fact, it's quite similar to what you already know
about variables in general. Just think of T as a special kind of variable,
whose "value" will be whatever type you pass in; this can be any class
type, any interface type, or even another type variable. It just can't be
any of the primitive data types. In this context, we also say that T is a
formal type parameter of the Box class.
/**
* Generic version of the Box class.
*/
public class Box<T> {
public T get() {
return t;
}
}
Box<Integer> integerBox;
162 162
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
the Box class itself. Like any other variable declaration, this code does
not actually create a new Box object. It simply declares that
integerBox will hold a reference to a "Box of Integer", which is
how Box<Integer> is read.
To instantiate this class, use the new keyword, as usual, but place
<Integer> between the class name and the parenthesis:
Or, you can put the entire statement on one line, such as:
BoxDemo3.java:5: add(java.lang.Integer) in
Box<java.lang.Integer>
cannot be applied to (java.lang.String)
integerBox.add("10");
^
1 error
It's important to understand that type variables are not actually types
themselves. In the above examples, you won't find T.java or
T.class anywhere on the filesystem. Furthermore, T is not a part of
the Box class name. In fact, during compilation, all generic information
163 163
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
You will see these names used throughout the Java SE API and the rest
of this tutorial.
/**
* This version introduces a generic method.
*/
public class Box<T> {
private T t;
public T get() {
return t;
164 164
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
}
public <U> void inspect(U u){
System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
}
T: java.lang.Integer
U: java.lang.String
To use this method, your code would look something like the following:
165 165
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Box.<Crayon>fillBoxes(red, crayonBoxes);
Here, we have explicitly provided the type to be used as U, but more
often than not, this can be left out and the compiler will infer the type
that's needed:
4.0 CONCLUSION
Specifically, you learned that generic type declarations can include one
or more type parameters; you supply one type argument for each type
parameter when you use the generic type. You also learned that type
parameters can be used to define generic methods and constructors.
Bounded type parameters limit the kinds of types that can be passed into
a type parameter; they can specify an upper bound only. Wildcards
represent unknown types, and they can specify an upper or lower bound.
5.0 SUMMARY
What you have learned in this unit is focused on generics, their methods
and constructors.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
166 166
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
167 167
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
MODULE 5 ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is an Algorithm?
3.2 Algorithm’s Performance
3.3 Algorithm Analysis
3.3.1 Worst-Case Complexity
3.3.2 Average-Case Complexity
3.4 Optimality
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
define an algorithm
explain an algorithm’s performance
describe algorithm analysis
explain the notion of an optimal algorithm.
168 168
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The most famous algorithm in history dates well before the time of the
ancient Greeks: this is Euclid's algorithm for calculating the greatest
common divisor of two integers.
169 169
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
c2g(n)
f(n)
c1g(n)
n
no
f(n) = (g(n))
170 170
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
cg(n)
f(n)
no n
f(n) = O(g(n))
f(n)
cg(n)
n
n f(n) = (g(n))
171 171
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The running time for any given size input will be lower than the upper
bound except possibly for some values of the input where the maximum
is reached.
The running time for any given size input will be the average number of
operations over all problem instances for a given size.
3.4 Optimality
In this unit you have learned about algorithms, their performance and
analysis. You have also been able to understand the optimality of an
algorithm.
5.0 SUMMARY
172 172
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
http://java.sun.com/docs/books/tutorial/java/concepts/index.html
http://cs.wwc.edu/~aabyan/OOP/
173 173
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Vectors
3.2 Addition of Two Vectors
3.3 Multiplication of a Vector by a Scalar
3.4 Dot Product and Norm
3.5 Matrices
3.6 Matrix Addition
3.7 Matrix Multiplication
3.8 Transpose
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will learn about vectors and matrices. Simple arithmetic
operations will also be carried out on the vectors and matrices.
2.0 OBJECTIVES
identify a vector
identify a matrix
add and multiply vectors
add and multiply matrices
determine the transpose of a matrix.
3.1 Vectors
where ui are called the components of u. If all the u i are zero i.e., ui = 0,
then u is called the zero vector.
Given vectors u and v are equal i.e., u = v, if they have the same number
of components and if corresponding components are equal.
174 174
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The product of a scalar, k, and a vector, u, i.e., ku, is the vector obtained
by multiplying each component of u by k:
The dot product or inner product of vectors u = (u1, u2, . . . , un) and v =
(v1, v2, . . . , vn) is denoted by u.v and defined by
3.5 Matrices
A=
175 175
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The m horizontal n-tuples are called the rows of A, and the n vertical
m-tuples, its columns. Note that the element, aij, called the ij-entry,
appear in the ith row and the jth column.
Let A and B be two matrices of the same size. The sum of A and B is
written as A + B and obtained by adding corresponding elements from A
and B.
A+B =
Suppose A and B are two matrices such that the number of columns of
A is equal to number of rows of B. Say matrix A is an m×p matrix and
matrix B is a p×n matrix. Then the product of A and B is the m×n matrix
whose ij-entry is obtained by multiplying the elements of the ith row of
A by the corresponding elements of the jth column of B and then adding
them.
3.8 Transpose
176 176
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about vectors and matrices. You have also
learned how to carry out addition and multiplication on vectors and
matrices.
5.0 SUMMARY
784
Find the transpose of the matrix
653
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
177 177
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
http://www.purplemath.com/modules/variable.htm
178 178
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Greedy Algorithm Overview
3.2 Greedy Algorithm Approach
3.3 Features of Problems Solved by Greedy Algorithm
3.4 Structure Greedy Algorithm
3.5 Definitions of Feasibility
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
What you will learn in this unit borders on greedy algorithms. The
greedy algorithm approach and functions will equally be discussed.
2.0 OBJECTIVES
179 179
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
180 180
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about greedy algorithms. You have also
been able to identify a promising feasible set.
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
181 181
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Divide-and-Conquer Algorithm
3.2 Binary Search
3.3 Sequential Search
3.4 Analysis
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
Breaking the problem into several sub-problems that are similar to the
original problem but smaller in size,
Solve the sub-problem recursively (successively and independently),
and then
Combine these solutions to subproblems to create a solution to the
original problem.
182 182
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Formally, find the index i such that 1 ≤ i ≤ n+1 and A[i-1] < x ≤ A[i].
for i = 1 to n do
if A [i] ≥ q then
return index i
return n + 1
3.4 Analysis
This algorithm clearly takes a θ(r), where r is the index returned. This is
Ω(n) in the worst case and O(1) in the best case.
4.0 CONCLUSION
183 183
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
184 184
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 5 ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Dynamic Programming
3.2 The Principle of Optimality
3.3 Dynamic Programming Algorithm
3.4 Analysis
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
185 185
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Bottom-up means
186 186
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
The finishing times are in a sorted array f[i] and the starting times are in
array s[i]. The array m[i] will store the value mi, where mi is the size of
the largest of mutually compatible activities among activities {1, 2, . . . ,
i}. Let BINARY-SEARCH(f, s) returns the index of a number i in the
sorted array f such that f(i) ≤ s ≤ f[i + 1].
for i =1 to n
do m[i] = max(m[i-1], 1+ m [BINARY-SEARCH(f, s[i])])
We have P(i] = 1 if activity i is in optimal selection, and P[i] = 0
otherwise
i=n
while i > 0
do if m[i] = m[i-1]
then P[i] = 0
i=i–1
else
i = BINARY-SEARCH (f, s[i])
P[i] = 1
3.4 Analysis
4.0 CONCLUSION
In this unit, you have learned about dynamic programming. You have
also gained insight of bottom-up technique and the principle of
optimality.
187 187
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
What you have learned in this unit concerns dynamic programming and
its analysis.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
188 188
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Graph Theory
3.2 Digraph
3.3 Algorithm Transpose
3.4 Algorithm Matrix Transpose
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, the student will gain knowledge of the graph theory and its
applications. The unit describes the digraph and determines the
transpose of an algorithm.
2.0 OBJECTIVES
189 189
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Connection problems
Scheduling problems
Transportation problems
Network analysis
Games and Puzzles.
3.2 Digraph
V = {1, 2, 3, 4}
E = { (1, 2), (2, 4), (4, 2) (4, 1)}
The definition of graph implies that a graph can be drawn just knowing
its vertex-set and its edge-set. For example, our first example
190 190
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
has vertex set V and edge set E where: V = {1,2,3,4} and E = {(1,2),
(2,4),(4,3),(3,1),(1,4),(2,1),(4,2),(3,4),(1,3),(4,1). Notice that each edge
seems to be listed twice.
Another example, the following Petersen Graph G=(V,E) has vertex set,
V, and edge set E where: V = {1,2,3,4}and E ={(1,2),(2,4),(4,3),(3,1),
(1,4),(2,1),(4,2),(3,4),(1,3),(4,1)}.
191 191
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
The graph theory and digraph were considered in this unit. You have
also learned about algorithmic transpose.
5.0 SUMMARY
What you have learned in this unit concerns graph theory and
algorithms.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
192 192
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 2 SORTING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Sorting
3.2 Internal Sort
3.3 External Sort
3.4 Memory Requirement
3.5 Stability
3.6 Classes of Sorting Algorithms
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignments
7.0 References/Further Readings
1.0 INTRODUCTION
This unit considers sorting algorithm. It delves into the two kinds of
sorting as well as the classes of sorting.
2.0 OBJECTIVES
3.1 Sorting
If the file to be sorted will fit into memory or equivalently, if it will fit
into an array, then the sorting method is called internal. In this method,
any record can be accessed easily.
193 193
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
800
700
600
500
400
300
200
100
0
10 100 1000 10000 25000 50000 75000 100000
n
194 194
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about sorting algorithm. You have also
been able to identify classes of sorting algorithm.
5.0 SUMMARY
What you have learned borders on sorting algorithms and their classes.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
195 195
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
196 196
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Bubble Sort
3.2 Memory Requirement
3.3 Implementation
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
197 197
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.3 Implementation
void bubbleSort(int numbers[], int array_size)
{
int i, j, temp;
for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
198 198
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
In this unit, you have learned about bubble sort. You have also learned
about its memory requirement and implementation.
5.0 SUMMARY
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
199 199
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
http://www.cs.sunysb.edu/~skiena/214/lectures/
200 200
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Insertion Sort
3.2 Analysis
3.3 Stability
3.4 Extra Memory
3.5 Implementation
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit considers insertion and its analysis. You will equally learn
about the stability and implementation of insertion sort.
2.0 OBJECTIVES
If the first few objects are already sorted, an unsorted object can be
inserted in the sorted set in proper place. This is called insertion sort. An
algorithm considers the elements one at a time, inserting each in its
suitable place among those already considered (keeping them sorted).
201 201
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.2 Analysis
Best-Case
The while-loop in line 5 executed only once for each j. This happens if
given array A is already sorted.
T(n) = an + b = O(n)
It is a linear function of n.
Worst-Case
The worst-case occurs, when line 5 executed j times for each j. This can
happen if array A starts out in reverse order
T(n) = an2 + bc + c = O(n2)
It is a quadratic function of n.
202 202
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.3 Stability
Since multiple keys with the same value are placed in the sorted array in
the same order that they appear in the input array, Insertion sort is
stable.
For Insertion sort we say the worst-case running time is θ(n2), and the
best-case running time is θ(n).
Insertion sort uses no extra memory it sorts in place.
The time of Insertion sort depends on the original order of an input. It
takes a time Ω(n2) in the worst-case, despite the fact that a time in order
of n is sufficient to solve large instances in which the items are already
sorted.
3.5 Implementation
4.0 CONCLUSION
In this unit you have learned about insertion sort. You have also learned
about the analysis stability and implementation of insertion sort.
203 203
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
5.0 SUMMARY
What you have learned in this unit borders on insertion sort, its analysis
and implementation.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
204 204
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
UNIT 5 ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Selection Sorting
3.2 Straight Selection Sorting
3.3 Implementation of the Selection Sort
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
Because the elements are added to the sorted sequence in order, they are
always added at one end. This is what makes selection sorting different
from insertion sorting. In insertion sorting, elements are added to the
sorted sequence in an arbitrary order. Therefore, the position in the
205 205
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
206 206
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
207 207
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In all n-1, iterations of the outer loop are needed to sort the
array. Notice that exactly one swap is done in each iteration
of the outer loop. Therefore, n-1 data exchanges are needed
to sort the list.
4.0 CONCLUSION
208 208
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
In this unit you have learned about selection sort and its implementation.
You have also learned about straight selection sort.
5.0 SUMMARY
What you have learned in this unit borders on selection sort and its
implementation.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
209 209
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Merge Sorting
3.2 Implementation
3.3 Merging
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
210 210
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
Figure 1.1 illustrates the operation of the two-way merge sort algorithm.
211 211
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
3.2 Implementation
3.3 Merging
and
are both sorted. The merge method merges the two sorted
subsequences using the temporary array, tempArray. It then copies
the merged (and sorted) sequence into the array at
212 212
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
213 213
CIT 216 CIT 216 FUNDAMENTALS OF DATA
STRUCTURESTRUCTURES
4.0 CONCLUSION
Specifically, you learned about merge sorting. You would have also
learned about steps to be adopted in sorting a sequence of elements. The
implementation of TwoWayMergeSorter was also considered.
5.0 SUMMARY
What you have learned in this unit is focused on merge sorting and its
implementation.
Deitel, H.M. and Deitel, P.J. (1998). C++ How to Programme (2nd
Edition), New Jersey: Prentice Hall.
Ford, W. and Topp, W. (2002). Data Structures with C++ Using the
STL (2nd Edition), New Jersey: Prentice Hall.
Online Resources
http://www.gnu.org/manual/emacs-20.3/emacs.html
http://www.indiana.edu/~ucspubs/b131
http://yoda.cis.temple.edu:8080/UGAIWWW/help
http://www.cs.sunysb.edu/~skiena/214/lectures/
214 214