(Ebook) Data Structures and Algorithms in C# by Michael McMillan ISBN 9780521670159, 0521670152 download
(Ebook) Data Structures and Algorithms in C# by Michael McMillan ISBN 9780521670159, 0521670152 download
https://ebooknice.com/product/data-structures-and-algorithms-
in-c-979682
https://ebooknice.com/product/data-structures-and-algorithms-
using-c-1821676
https://ebooknice.com/product/data-structures-and-algorithms-with-
javascript-37208884
https://ebooknice.com/product/data-structures-and-algorithms-in-c-5060258
https://ebooknice.com/product/data-structures-and-algorithms-in-c-4630542
(Ebook) Problem Solving in Data Structures & Algorithms Using C#
by Hemant Jain
https://ebooknice.com/product/problem-solving-in-data-structures-
algorithms-using-c-38289180
https://ebooknice.com/product/data-structures-algorithms-and-applications-
in-c-5912596
https://ebooknice.com/product/data-structures-and-algorithms-in-
java-1475214
https://ebooknice.com/product/data-structures-and-algorithms-in-
java-4944334
https://ebooknice.com/product/problem-solving-in-data-structures-
algorithms-using-c-11826850
P1: FCW
0521670152pre CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 20:59
Cambridge University Press has no responsibility for the persistence or accuracy of urls
for external or third-party internet websites referred to in this publication, and does not
guarantee that any content on such websites is, or will remain, accurate or appropriate.
P1: FCW
0521670152pre CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 20:59
Contents
Chapter 1
An Introduction to Collections, Generics, and the
Timing Class 1
Chapter 2
Arrays and ArrayLists 26
Chapter 3
Basic Sorting Algorithms 42
Chapter 4
Basic Searching Algorithms 55
Chapter 5
Stacks and Queues 68
Chapter 6
The BitArray Class 94
Chapter 7
Strings, the String Class, and the StringBuilder Class 119
Chapter 8
Pattern Matching and Text Processing 147
v
P1: FCW
0521670152pre CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 20:59
vi CONTENTS
Chapter 9
Building Dictionaries: The DictionaryBase Class and the
SortedList Class 165
Chapter 10
Hashing and the Hashtable Class 176
Chapter 11
Linked Lists 194
Chapter 12
Binary Trees and Binary Search Trees 218
Chapter 13
Sets 237
Chapter 14
Advanced Sorting Algorithms 249
Chapter 15
Advanced Data Structures and Algorithms for Searching 263
Chapter 16
Graphs and Graph Algorithms 283
Chapter 17
Advanced Algorithms 314
References 339
Index 341
P1: FCW
0521670152pre CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 20:59
Preface
viii PREFACE
Simple timing tests are used to compare the performance of the data structures
and algorithms discussed in the book.
PREREQUISITES
The only prerequisite for this book is that the reader have some familiarity
with the C# language in general, and object-oriented programming in C# in
particular.
CHAPTER-BY-CHAPTER ORGANIZATION
PREFACE ix
ACKNOWLEDGEMENTS
There are several different groups of people who must be thanked for helping
me finish this book. First, thanks to a certain group of students who first
sat through my lectures on developing data structures and algorithms. These
students include (not in any particular order): Matt Hoffman, Ken Chen, Ken
Cates, Jeff Richmond, and Gordon Caffey. Also, one of my fellow instructors
at Pulaski Technical College, Clayton Ruff, sat through many of the lectures
P1: FCW
0521670152pre CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 20:59
x PREFACE
C HAPTER 1
An Introduction to
Collections, Generics,
and the Timing Class
1
P1: IBE
0521670152c01 CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 21:2
COLLECTIONS DEFINED
A collection is a structured data type that stores data and provides operations
for adding data to the collection, removing data from the collection, updating
data in the collection, as well as operations for setting and returning the values
of different attributes of the collection.
Collections can be broken down into two types: linear and nonlinear. A
linear collection is a list of elements where one element follows the previous
element. Elements in a linear collection are normally ordered by position
(first, second, third, etc.). In the real world, a grocery list is a good example
of a linear collection; in the computer world (which is also real), an array is
designed as a linear collection.
Nonlinear collections hold elements that do not have positional order
within the collection. An organizational chart is an example of a nonlinear
collection, as is a rack of billiard balls. In the computer world, trees, heaps,
graphs, and sets are nonlinear collections.
Collections, be they linear or nonlinear, have a defined set of properties that
describe them and operations that can be performed on them. An example
of a collection property is the collections Count, which holds the number of
items in the collection. Collection operations, called methods, include Add
(for adding a new element to a collection), Insert (for adding a new element
to a collection at a specified index), Remove (for removing a specified element
from a collection), Clear (for removing all the elements from a collection),
Contains (for determining if a specified element is a member of a collec-
tion), and IndexOf (for determining the index of a specified element in a
collection).
COLLECTIONS DESCRIBED
The most common example of a direct access collection is the array. We define
an array as a collection of elements with the same data type that are directly
accessed via an integer index, as illustrated in Figure 1.1.
P1: IBE
0521670152c01 CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 21:2
Collections Described 3
Arrays can be static so that the number of elements specified when the array
is declared is fixed for the length of the program, or they can be dynamic, where
the number of elements can be increased via the ReDim or ReDim Preserve
statements.
In C#, arrays are not only a built-in data type, they are also a class. Later
in this chapter, when we examine the use of arrays in more detail, we will
discuss how arrays are used as class objects.
We can use an array to store a linear collection. Adding new elements to an
array is easy since we simply place the new element in the first free position
at the rear of the array. Inserting an element into an array is not as easy (or
efficient), since we will have to move elements of the array down in order
to make room for the inserted element. Deleting an element from the end of
an array is also efficient, since we can simply remove the value from the last
element. Deleting an element in any other position is less efficient because,
just as with inserting, we will probably have to adjust many array elements
up one position to keep the elements in the array contiguous. We will discuss
these issues later in the chapter. The .NET Framework provides a specialized
array class, ArrayList, for making linear collection programming easier. We
will examine this class in Chapter 3.
Another type of direct access collection is the string. A string is a collection
of characters that can be accessed based on their index, in the same manner we
access the elements of an array. Strings are also implemented as class objects
in C#. The class includes a large set of methods for performing standard
operations on strings, such as concatenation, returning substrings, inserting
characters, removing characters, and so forth. We examine the String class in
Chapter 8.
C# strings are immutable, meaning once a string is initialized it cannot be
changed. When you modify a string, a copy of the string is created instead of
changing the original string. This behavior can lead to performance degrada-
tion in some cases, so the .NET Framework provides a StringBuilder class that
enables you to work with mutable strings. We’ll examine the StringBuilder in
Chapter 8 as well.
The final direct access collection type is the struct (also called structures
and records in other languages). A struct is a composite data type that holds
data that may consist of many different data types. For example, an employee
P1: IBE
0521670152c01 CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 21:2
set {
fname = firstName;
}
}
public string middleName {
get {
return mname;
}
set {
mname = middleName;
}
}
Collections Described 5
return lname;
}
set {
lname = lastName;
}
}
using System;
int num;
string snum;
Console.Write("Enter a number: ");
snum = Console.ReadLine();
num = Int32.Parse(snum);
Console.WriteLine(num);
}
}
An unordered list consists of elements in any order. The order of a list makes
a big difference when performing searches on the data on the list, as you’ll see
in Chapter 2 when we explore the binary search algorithm versus a simple
linear search.
Collections Described 7
David David
Raymond Raymond
Mike Mike
Some types of linear lists restrict access to their data elements. Examples
of these types of lists are stacks and queues. A stack is a list where access is
restricted to the beginning (or top) of the list. Items are placed on the list
at the top and can only be removed from the top. For this reason, stacks are
known as Last-in, First-out structures. When we add an item to a stack, we
call the operation a push. When we remove an item from a stack, we call that
operation a pop. These two stack operations are shown in Figure 1.3.
The stack is a very common data structure, especially in computer systems
programming. Stacks are used for arithmetic expression evaluation and for
balancing symbols, among its many applications.
A queue is a list where items are added at the rear of the list and removed
from the front of the list. This type of list is known as a First-in, First-out struc-
ture. Adding an item to a queue is called an EnQueue, and removing an item
from a queue is called a Dequeue. Queue operations are shown in Figure 1.4.
Queues are used in both systems programming, for scheduling operating
system tasks, and for simulation studies. Queues make excellent structures
for simulating waiting lines in every conceivable retail situation. A special
type of queue, called a priority queue, allows the item in a queue with the
highest priority to be removed from the queue first. Priority queues can be
used to study the operations of a hospital emergency room, where patients
with heart trouble need to be attended to before a patient with a broken arm,
for example.
The last category of linear collections we’ll examine are called generalized
indexed collections. The first of these, called a hash table, stores a set of data
Mike Mike
Raymond De Queue
David Raymond
Beata David
En Queue Beata
Bernica Bernica
“Paul E. Spencer”
37500
“Information Systems”
values associated with a key. In a hash table, a special function, called a hash
function, takes one data value and transforms the value (called the key) into
an integer index that is used to retrieve the data. The index is then used to
access the data record associated with the key. For example, an employee
record may consist of a person’s name, his or her salary, the number of years
the employee has been with the company, and the department he or she works
in. This structure is shown in Figure 1.5. The key to this data record is the
employee’s name. C# has a class, called HashTable, for storing data in a hash
table. We explore this structure in Chapter 10.
Another generalized indexed collection is the dictionary. A dictionary is
made up of a series of key–value pairs, called associations. This structure
is analogous to a word dictionary, where a word is the key and the word’s
definition is the value associated with the key. The key is an index into the
value associated with the key. Dictionaries are often called associative arrays
because of this indexing scheme, though the index does not have to be an
integer. We will examine several Dictionary classes that are part of the .NET
Framework in Chapter 11.
Hierarchical Collections
Nonlinear collections are broken down into two major groups: hierarchical
collections and group collections. A hierarchical collection is a group of items
divided into levels. An item at one level can have successor items located at
the next lower level.
One common hierarchical collection is the tree. A tree collection looks like
an upside-down tree, with one data element as the root and the other data
values hanging below the root as leaves. The elements of a tree are called
nodes, and the elements that are below a particular node are called the node’s
children. A sample tree is shown in Figure 1.6.
P1: IBE
0521670152c01 CUNY656/McMillan Printer: cupusbw 0 521 67015 2 February 17, 2007 21:2
Collections Described 9
Root
Trees have applications in several different areas. The file systems of most
modern operating systems are designed as a tree collection, with one directory
as the root and other subdirectories as children of the root.
A binary tree is a special type of tree collection where each node has no
more than two children. A binary tree can become a binary search tree, making
searches for large amounts of data much more efficient. This is accomplished
by placing nodes in such a way that the path from the root to a node where
the data is stored is along the shortest path possible.
Yet another tree type, the heap, is organized so that the smallest data value
is always placed in the root node. The root node is removed during a deletion,
and insertions into and deletions from a heap always cause the heap to reor-
ganize so that the smallest value is placed in the root. Heaps are often used
for sorts, called a heap sort. Data elements stored in a heap can be kept sorted
by repeatedly deleting the root node and reorganizing the heap.
Several different varieties of trees are discussed in Chapter 12.
Group Collections
A nonlinear collection of items that are unordered is called a group. The three
major categories of group collections are sets, graphs, and networks.
A set is a collection of unordered data values where each value is unique.
The list of students in a class is an example of a set, as is, of course, the integers.
Operations that can be performed on sets include union and intersection. An
example of set operations is shown in Figure 1.7.
Random documents with unrelated
content Scribd suggests to you:
demands a visit. On the top of the Aigoual a dinner and a bed may
be obtained at the Observatory. Bramabiau may also be visited from
Le Vigan. The rivulet of the Bonheur, that descends from the Col de
Séyrerède near the Aigoual, after flowing over granite and schist,
encounters a mass of Dolomitic limestone, through which it has
bored a channel for a distance of 1,200 feet. The tunnel through
which it flows is in one place open to the sky through the falling in of
the roof. The name Bramabiau given to this cavern traversed by a
stream is onomatopœic, and signifies the bellowing of a bull, as the
water in time of flood gives forth angry sounds.
Nothing surprises one more than the apparent inadequacy of the
means to the end attained. The Bonheur is but a small stream, yet
the work it has achieved is tremendous. But it must be borne in
mind that where stands Camprieu was once a lake, the water held
back by the barrier of limestone, and that the accumulated force was
brought to bear on the rock to effect this tunnel of drainage.
Moreover, the rock itself was full of holes like a sponge, with large
vaults like huge bubbles in its interior, so that it was not a solid mass
through which the stream had to bore its way. It was further aided
by several springs rising within the rock, all working in their several
courses to effect their escape.
Bramabiau
Florac hardly comes within the range that I have marked out for
description, and yet some words must be given to it, as it was the
centre of the Cevenol revolt, and was the scene of several conflicts
and of the execution of Camisards.
It is a very dirty place, originally walled; the houses were so
crowded that the streets were contracted to the narrowest possible
width. One has to be careful not to walk down them before eight
o'clock in the morning, as all the slops are thrown from the windows
into the street, and may fall on the head of the incautious
passenger; and here no warning call is given, as in the narrow lanes
of old Edinburgh, to put the man in the street on his guard. What is
cast forth remains where it falls till torrential rains sweep away the
accumulated filth of weeks and even months. In the Languedoc
towns that reek with evil odours, in a country too where the hillsides
are redolent with aromatic herbs, lavender, sage, marjoram,
rosemary, beds of violets, thyme in sheets, one can hardly help
repeating the lines of Bishop Heber:
"What though the spicy breezes
Blow sweet o'er Ceylon's isle,
And every prospect pleases,
Yet only man is vile."
FOOTNOTE
[12] Martel: Les Cévennes. Paris, 1891.
CHAPTER XVI
THE LAND OF FERDINAND FABRE
This is what Fabre says of the natives. There are two types not
due to difference of blood, but of surroundings and of occupations.
We are now in the department of Hérault, of Lower Languedoc, and
I may be allowed a few words on the mixture of peoples of diverse
origin that have been fused together into a homogeneous race.
From a period before history began, this country was inhabited by
populations of diverse origins, habits, and language, drawn thither
by the delicious climate, its natural resources, or simply by the
chance of migration. One fact characterises the establishment of the
tribes or nationalities in these parts; so far as we can judge, it was
their attitude towards the people who preceded them. If some of
them swept away the indigenous race, more often they planted
themselves beside the earlier population peaceably and fused with
them. Most of these invaders seem to have possessed gentle
manners, and were not goaded on by the passion for extermination,
for which there was no provocation or need, as the land was wide
and rich enough to sustain all. This mode of colonisation had the
result of filling Lower Languedoc with very heterogeneous
inhabitants, the complexity of which explains the apparent
contradictions of early writers. But on one point these writers are
unanimous: the variety of races or mixtures that occupied the land in
Gallia Narbonensis. In the first century before Christ, Cicero notices
this; and in the fourth century after Christ, Ausonius sang: "Who can
record all thy ports, thy mountains and thy lakes, who the diversity
of thy peoples, their vestures and their languages?"
The most ancient inhabitants recorded were the Iberians, who
extended their domination over the Spanish peninsula and to the
Rhône on the east, which formed the boundary between them and
the Ligurians. But at a time difficult to determine these latter crossed
the river and invaded the territories of the Iberians. But instead of
expelling the conquered peoples, the Ligurians, having an aptitude
for absorption, mingled with those whom they had subdued and
formed the mixed race of the Iberian-Ligurian. There was, however,
already in the land a third nation, that of the Umbranici, apparently
the same as the Umbrians of Northern Italy. They have left their
name at Ambrussum, now Pont-Ambroise, on the Vidourle. Twenty-
three inscriptions remain, mostly in Gard, in an unknown tongue, but
written in Greek characters, that bears an affinity alike to the Ossian
and Umbrian language in Italy.
The Greek trade of Marseilles spread through the land. At Murviel,
a cyclopean enclosure, not many miles from Montpellier, have been
found Greek coins of Marseilles.
In the fourth century before the Christian era a new ethnic
element came to add to what already existed. The Gauls appeared in
the land. A branch of this stock was that of the Volci. These
established themselves between the Rhône and the Garonne, and
extended their authority over the Ibero-Ligurians. These new arrivals
seem to have treated the conquered much as the Ligurians had the
Iberians. They established themselves peaceably among them or
alongside of them. This was the more easy, for, as Strabo says,
though the Gauls belonged to a wholly different stock, yet they
resembled the Ligurians in their mode of life.
Their dominion was not for long—not for more than two centuries
—for in B.C. 121 their country was conquered by the Romans.
Such, then, is the origin of the population of Lower Languedoc,
and explains the diverse origin of the names of rivers, mountains
and towns, some Iberic, some Celtic, some Latin, some of
undiscoverable derivation, given perhaps by the Umbrian colony.
The staple of life in the Cévennes, mainly in the southern portion,
is not corn, but the chestnut. That is why we see this tree
everywhere, old and twisted, but sturdy still, young and vigorous
when recently planted. But unhappily a malady has broken out
among them, the cause of which has not been discovered with
certainty, nor has any remedy been found efficacious. In some years
the leaves fall in September, and the fruit comes to nothing,
reducing the people to a condition almost of famine. In order to
preserve the nuts through the winter and spring and prevent the
sprouting, they are subjected to desiccation in clèdes that may be
seen as a part of the outbuildings of every farmhouse and of many
cottages.
The Spanish chestnut is a beautiful tree. It was indigenous in
England. A few years ago I was draining a field by the river, and cut
down to glacial clay nearly nine feet below the surface, and lying on
this was a huge tree, black as ebony. With great labour I had it
removed to the sawmill, thinking it to have been black bog oak. It
was Spanish chestnut, and since then others have been found in the
same valley. It seems willing to grow anywhere. The peasants build
up terraces no larger than a doormat, and it grows there. But where
there is plenty of soil it will grow much more vigorously than on a
ledge of rock.
"I wish," said R. L. Stevenson, "I could convey a notion of the growth of
these noble trees; of how they strike out boughs like the oak, and trail
sprays of drooping foliage like the willow; of how they stand as upright
fluted columns like the pillars of a church; or like the olive, from the most
shattered bole can put out smooth and youthful shoots, and begin a new
life upon the ruins of the old. Thus they partake of the nature of many
different trees; and even their prickly top-knots, seen near at hand against
the sky, have a certain palm-like air that impresses the imagination. But
this individuality, although compounded of so many elements, is but the
richer and the more original. And to look down upon a level filled with
these knolls of foliage, or to see a clan of old unconquerable chestnuts
cluster like herded elephants upon the spurs of a mountain, is to rise to
higher thoughts of the powers that are in Nature."
"After the fourth couplet the ballad was interrupted. Our Cevenols
raised their boughs, brandished the leaves, and made therewith the sign
of the cross.
'On your knees!' said the old woman, extending her hand. The beaters
knelt at once. Then, all at once, from a thousand sturdy breasts young for
the most part, rolled forth the final verse of the Complainte du
Châtaignier. It was as grand, as beautiful, as sublime as any psalm, any
hymn I have heard in any church.
Cheesemakers, Roquefort
But the market is not one of cattle and corn only, it is of human
beings as well, for hither come the shepherds to hire boys to attend
during the year on the sheep and herds of swine. These lads are
locally called pillards, and the token that one has been engaged is
that the shepherd buys the boy a pair of new sabots out of his own
money, a sort of investiture in the pastoral office. These lads and the
shepherds lead a lonely life in the mountains. The boys are not
unkindly treated, for the Cevenol, if rough and silent, has a gentle
and kindly heart. But what a life for a growing boy in wild nature,
among mountains and shrubs, birds of all kinds, and creeping things
innumerable, and at night with the stars shining above his head with
a sharpness and intensity as though they stabbed him to the heart,
but left an exquisite pain behind. He learns to know the signs of the
times, the winds, the voices of nature, to distinguish one bird's note
from another, and to ascertain the virtues of the aromatic herbs on
the limestone causse. The life may be hard, but it is healthy both to
body and mind and soul.
FOOTNOTE:
[13] Ferd. Troubat: Danse des Treilles. Toulouse, 1900.
CHAPTER XVII
THE HÉRAULT
S. Guilhem-le-Désert
In 1209 Aimar Guilhem, seigneur of Clermont, was the ally of the
unfortunate Raymond, Count of Toulouse, against whom Innocent
III. hurled the thunders of excommunication because he would not
butcher and burn his subjects, who had embraced the Albigensian
heresy; and Aimar was accordingly involved in his sentence.
Innocent called together the riff-raff of Europe to join in a crusade
against Raymond, promising life eternal and absolution from all sins
to those who would join in an indiscriminate slaughter of the
Albigenses, and placed Simon de Montfort at the head of this horde
of the Children of God, as they called themselves, who swept over
the land committing indescribable horrors. After the massacre of the
inhabitants of Béziers by the crusaders, Aimar retired to his castle
and awaited events. His conduct may have been prudent, as he
saved the town from sack and slaughter, but it was unworthy of him;
as had he roused the country of Lodève, he would have menaced
the rear of Simon de Montfort, and might have forced this
commander of the soldiers of the Papacy to deal less cruelly with the
seigneurs of Languedoc, whom he robbed of their domains with
impunity.
On the Place under trees is a monument, surmounted by a bust of
Peyrolles, a potter of Clermont, who composed verses in the
Languedoc dialect. He became jealous of the fame acquired by
Jasmin, the hairdresser of Agen, the great vernacular poet, and sent
him a challenge. "I will go to Montpellier any day and hour you
choose to name. Let four men of literary notoriety give us three
themes on which to compose poems in twenty-four hours; and let us
be shut up in one room, with no admission of any one to us or of
anything but our food—and see who in the time will turn out most
poetry." Jasmin replied that he declined the contest. For his part, he
could not produce verses as fast as Peyrolles could pots; his powers
did not reach further than the composition of two or three verses in
a day.
In the Cirque, Mourèze
Group at Mourèze
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com