103260880
103260880
103260880
com
OR CLICK HERE
DOWLOAD EBOOK
https://ebooknice.com/product/data-structures-algorithms-and-
applications-in-c-5912596
ebooknice.com
ebooknice.com
(Ebook) Data Structures and Algorithms in C# by Michael
McMillan ISBN 9780521670159, 0521670152
https://ebooknice.com/product/data-structures-and-algorithms-
in-c-979682
ebooknice.com
https://ebooknice.com/product/data-structures-and-algorithms-
in-c-4630542
ebooknice.com
ebooknice.com
https://ebooknice.com/product/the-c-standard-library-fourth-edition-
includes-c-23-49417210
ebooknice.com
Marcin Jamro
BIRMINGHAM - MUMBAI
C# Data Structures and
Algorithms
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any
form or by any means, without the prior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express or implied.
Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages
caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the
accuracy of this information.
ISBN 978-1-78883-373-8
www.packtpub.com
mapt.io
Mapt is an online digital library that gives you full access to over
5,000 books and videos, as well as industry leading tools to help you
plan your personal development and advance your career. For more
information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical
eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
developers and tech professionals, just like you, to help them share
their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are
recruiting an author for, or submit your own idea.
Table of Contents
Title Page
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
Conventions used
Get in touch
Reviews
1. Getting Started
Programming language
Data types
Value types
Structs
Enumerations
Reference types
Strings
Object
Dynamic
Classes
Interfaces
Delegates
Writing to output
Summary
Arrays
Single-dimensional arrays
Multi-dimensional arrays
Jagged arrays
Sorting algorithms
Selection sort
Insertion sort
Bubble sort
Quicksort
Simple lists
Array list
Generic list
Example – average value
Implementation
Example – spin the wheel
Summary
3. Stacks and Queues
Stacks
Example – reversing words
Priority queues
Example – call center with priority support
Summary
4. Dictionaries and Sets
Hash tables
Example – phone book
Dictionaries
Example – product location
"Sorted" sets
Example – removing duplicates
Summary
5. Variants of Trees
Basic trees
Implementation
Node
Tree
Binary trees
Implementation
Node
Tree
Tree
Lookup
Insertion
Removal
Example – BST visualization
AVL trees
Implementation
Example – keep the tree balanced
Red-black trees
Implementation
Example – RBT-related features
Binary heaps
Implementation
6. Exploring Graphs
Concept of graphs
Applications
Representation
Adjacency list
Adjacency matrix
Implementation
Node
Edge
Graph
Example – undirected and unweighted edges
Example – directed and weighted edges
Traversal
Depth-first search
Breadth-first search
Minimum spanning tree
Kruskal's algorithm
Prim's algorithm
Example – telecommunication cable
Coloring
Summary
7. Summary
Classification of data structures
Diversity of applications
Arrays
Lists
Stacks
Queues
Dictionaries
Sets
Trees
Heaps
Graphs
The last word
Other Books You May Enjoy
Leave a review - let other readers know what you think
Preface
As a developer, you have certainly heard about various data
structures and algorithms. However, have you ever thought
profoundly about them and their impact on the performance of your
applications? If not, it is high time to take a look at this topic, and
this book is a great place to start!
The book covers many data structures, starting with simple ones,
namely arrays and a few of their variants, as representatives of
random access data structures. Then, lists are introduced, together
with their sorted variant. The book also explains limited access data
structures, based on stacks and queues, including a priority queue.
Following this, we introduce you to the dictionary data structure,
which allows you to map keys to values and perform fast lookup.
The sorted variant of the dictionary is supported, as well. If you
want to benefit from high-performance, set-related operations, you
can use another data structure, namely a hash set. One of the most
powerful constructs is a tree, which exists in a few variants, such as
a binary tree, a binary search tree, as well as a self-balancing tree
and a heap. The last data structure we analyze is a graph, which is
supported by many interesting algorithmic topics, such as graph
traversal, minimum spanning tree, node coloring, and finding the
shortest path in a graph. There is a lot of content ahead of you!
the right data structures and algorithms, as well as the impact it has
on the performance of the developed solution. The chapter briefly
introduces you to the topic of the C# programming language and
various data types—both value and reference. Then, it presents the
process of the installation and configuration of the IDE, as well as
the creation of a new project, developing the example application,
and debugging using breakpoints and the step-by-step technique.
Chapter 2, Arrays and Lists, covers scenarios of storing data using two
kinds of random access data structures, namely arrays and lists.
First, three variants of arrays are explained, that is, single-
dimensional, multi-dimensional, and jagged. You will also get to
know four sorting algorithms, namely selection, insertion, bubble
sort, and quicksort. The chapter also deals with a few variants of
lists, such as simple, sorted, double-linked, and circular-linked.
presents the basic tree, together with its implementation in C#, and
examples showing this in action. The chapter also introduces you to
binary trees, binary search trees, and self-balancing trees, namely
AVL and red-black trees. The remainder of the chapter is dedicated
to heaps as tree-based structures, that is, the binary, binomial, and
Fibonacci heaps.
Once the file is downloaded, please make sure that you unzip or
extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://githu
b.com/PacktPublishing/C-Sharp-Data-Structures-and-Algorithms. In case there's an
We also have other code bundles from our rich catalog of books and
videos available at https://github.com/PacktPublishing/. Check them out!
Download the color images
We also provide a PDF file that has color images of the
screenshots/diagrams used in this book. You can download it here: h
ttps://www.packtpub.com/sites/default/files/downloads/CSharpDataStructuresandAlgorit
hms_ColorImages.pdf .
Conventions used
There are a number of text conventions used throughout this book.
Piracy: If you come across any illegal copies of our works in any
form on the Internet, we would be grateful if you would provide us
with the location address or website name. Please contact us at
copyright@packtpub.com with a link to the material.
Did you know that replacing even one data structure with another
could cause the performance results to increase hundreds of times?
Does it sound impossible? Maybe, but it is true! As an example, I
would like to tell you a short story about one of the projects in which
I was involved. The aim was to optimize the algorithm of finding
connections between blocks on a graphical diagram. Such
connections should be automatically recalculated, refreshed, and
redrawn as soon as any block has moved in the diagram. Of course,
connections cannot go through blocks and cannot overlap other
lines, and the number of crossings and direction changes should be
limited. Depending on the size and the complexity of the diagram,
the performance results differ. However, while conducting tests, we
have received results in the range from 1 ms to almost 800 ms for
the same test case. What could be the most surprising aspect is that
such a huge improvement has been reached mainly by... changing
data structures of two sets.
Now, you could ask yourself the obvious question: which data
structures should I use in given circumstances and which algorithms
could be used to solve some common problems? Unfortunately, the
answer is not simple. However, within this book, you will find a lot of
information about data structures and algorithms, presented in the
context of the C# programming language, with many examples,
code snippets, and detailed explanations. Such content could help
you to answer the aforementioned questions while developing the
next great solutions, which could be used by many people all over
the world! Are you ready to start your adventure with data
structures and algorithms? If so, let's start!
Programming language
Data types
Installation and configuration of the IDE
Creating the project
Input and output
Launching and debugging
Programming language
As a developer, you have certainly heard about many programming
languages, such as C#, Java, C++, C, PHP, or Ruby. In all of
them, you can use various data structures, as well as implement
algorithms, to solve both basic and complex problems. However,
each language has its own specificity, which could be visible while
implementing data structures and accompanying algorithms. As
already mentioned, this book will focus only on the C# programming
language, which is also the main topic of this section.
As you can see, a Value type stores its actual Value directly in the
Stack memory, while a Reference type only stores a Reference
here. The actual value is located in the Heap memory. Therefore, it
is also possible to have two or more variables of a reference type that
reference exactly the same value.
One of them is the Boolean type (the bool keyword), which makes it
possible to store a logical value, that is, one of two values, namely
true or false.
As for storing integer values, you can use one of the following
types: Byte (the byte keyword), SByte (sbyte), Int16 (short), UInt16 (ushort),
Int32 (int), UInt32 (uint), Int64 (long), and UInt64 (ulong). They differ by the
You can assign a value to a variable using the equals sign (=), shown
as follows:
number = 500;
Of course, declaration and assignment could be performed in the
same line:
int number = 500;
concatenated with two dots to form the initials, that is, M.J., which
are stored as a value of the initials variable.
The Format static method could also be used for constructing the
string, as follows:
string note = string.Format("{0} {1} was born in {2}",
firstName, lastName.ToUpper(), year);
As the object type is the base entity for all value types, it means that
it is possible to convert a variable of any value type (for example, int
or float) to the object type, as well as to convert back a variable of the
object type to a specific value type. Such operations are named
boxing (the first one) and unboxing (the other). They are shown
as follows:
int age = 28;
object ageBoxing = age;
int ageUnboxing = (int)ageBoxing;
More information is available at: https://docs.microsoft.com/en-us/dotnet/csharp/language-refe
rence/keywords/object.
Dynamic
Apart from the types already described, the dynamic one is available
for developers. It allows the bypassing of type checking during
compilation so that you can perform it during the run time. Such a
mechanism is useful while accessing some application
programming interfaces (APIs), but it will not be used in this
book.
More information is available at: https://docs.microsoft.com/en-us/dotnet/csharp/language-refe
rence/keywords/dynamic.
Classes
As already mentioned, C# is an object-oriented language and
supports declaration of classes together with various members,
including constructors, finalizers, constants, fields, properties,
indexers, events, methods, and operators, as well as delegates.
Moreover, classes support inheritance and implementing interfaces.
Static, abstract, and virtual members are available, as well.
The Person class contains the _location private field with the default
value set as the empty string (string.Empty), two public properties (Name
and Age), a default constructor that sets a value of the Name property
to --- using the expression body definition, an additional
constructor that takes two parameters and sets values of properties,
the Relocate method that updates the value of the private field, as well
as the GetDistance method that calls the GetDistance static method from
the DistanceHelpers class and returns the distance between two cities in
kilometers.
You can create an instance of the class using the new operator. Then,
you can perform various operations on the object created, such as
calling a method, as shown as follows:
Person person = new Person("Mary", 20);
person.Relocate("Rzeszow");
float distance = person.GetDistance("Warsaw");
More information is available at: https://docs.microsoft.com/en-us/dotnet/csharp/language-refe
rence/keywords/class.
Random documents with unrelated
content Scribd suggests to you:
a stone roller for threshing rice and a shovel for winnowing. Manure,
consisting of horse and cow droppings, night soil and ashes, was
bought in the city at the rate of threepence per donkey load, and
used freely on the land, which was a rich alluvial loam; the frequent
storms also deposited layers of dust which were regarded as good
for the crops.
The house, which Isa Haji owned and had built room by room as he
could afford it, at a total cost (including the land) of £50, covered a
square of sixty feet. The guest-room, in which he lived during the
summer and in which the meals were cooked and served, was about
twenty feet square and was lighted by a hole in the roof. A mud
platform covered with felts, on which the family slept, occupied a
prominent position, and the chief piece of furniture was a carved box,
which held clothes and served as a bedstead. Above it was a shelf
full of Russian teapots. Off this room opened the store-room, in
which grain was kept for winter consumption and which served as
the living-room in winter. There was also a courtyard partly roofed in
with matting during the summer, in which grew a shady tree, and this
was the chief working room of the wife and daughters-in-law at that
season. Here we noticed a cradle, a spinning-wheel and various
pans. Two small rooms belonged to two unmarried sons, and the
rest of the square contained stabling, an oven and a store for dry
fodder.
THE SONS OF ISA HAJI PLOUGHING.
Page 304.
The home was managed by the wife and her three daughters-in-law,
who cooked the food, looked after the children and made the
clothes. They did not work in the fields, but spun the cotton into yarn,
which they wove into the rough white calico of which most of the
clothing of the poorer classes is fashioned.
The staple food of the family was bread made from millet, a grain
that is held to be more sustaining than wheat or rice. Isa Haji’s large
family consumed all his share of the crops, except the lucerne and
some of the melons, turnips, carrots and linseed, which were sold.
The oil of the linseed was used for cooking and lighting.
The chief meal of these peasant-farmers was eaten at sunset and
consisted of suyukash, a soup prepared from pieces of paste-like
macaroni and vegetables boiled in water. In the morning they took
tea with cream and salt, and fruit and bread were eaten at odd
hours. Meat, generally beef, appeared on their table only once a
week. There was plenty of this rude fare, supplemented by slices of
pumpkin eaten hot and by other delicacies; and Isa Haji’s sons
appeared healthy, their teeth being noticeably fine and sound. They
said that they suffered a good deal from lack of warmth in the winter,
as charcoal was dear and had to be used sparingly. They placed a
bowl of lighted charcoal under a wooden frame, over which a quilt
was thrown, and the family sat by day and slept by night under this
covering, with their feet towards the centre.
Isa Haji had been the tenant of the farm for more than ten years. It
included three small properties belonging to three Kashgar
merchants. Two-thirds of the lucerne, amounting in value to about
five pounds, and one half of the other crops, were paid over as rent.
He had no security of tenure, and could be turned out at will, but the
prospect of this appeared to him unlikely, and he expressed
satisfaction with his lot.
The farm paid revenue to the extent of 105 lbs. of wheat, a similar
quantity of millet and 2100 lbs. of chopped straw, Isa Haji and his
landlords each paying one half of the whole. There had also to be
met the demand of the Chinese authorities for forced labour on
public works and transport, but this was compounded for in money
and might come to the equivalent of two shillings per annum.
Nothing was paid for the use of irrigation water, and the taxation
represented less than 5 per cent of the two main crops. In the case
of villages situated at some distance from the city double this amount
may be taken by the tax collectors, who are more exacting in
proportion to their distance from headquarters.
To sum up, we have an oasis in which agriculture is not affected by
the rainfall, but depends entirely on the rivers. The peasants have
enough to eat, a good climate and neighbours in abundance. There
are few parts of the world where the people are so contented, and,
although discontent might perhaps bring an improvement of their lot,
it is pleasant to see such cheerful, friendly tillers of the soil leading a
healthy agricultural life, and to meet them returning home at night
singing their tuneful songs:
When her hour was come, no one was allowed to leave the house
unless upon business that was urgent, in which case no harm was
anticipated, provided that some article of dress was left behind. The
women of the neighbourhood assembled to help, and during the
delivery cried out with the idea of keeping the birth a secret, a
custom adopted from the Chinese. The newly born infant, too, was
carefully concealed from visitors.
If former children belonging to the parents have all died, which is,
alas, a frequent occurrence, the father, dressed as a beggar, takes
the baby to the bazar and begs from the shopkeepers small pieces
of calico, which are made into a shirt, the idea being to avoid
misfortune by thus humbling himself. Special names signifying “solid”
or “stay” or “may he stay!” are in such cases given to the child when
he is named, between the third and seventh day, by a mulla, who
first whispers the azan or call to prayer into his ear. On the fortieth
day the head of the infant is shaved and the hair buried. A sheep is
sacrificed and eaten on this occasion, while its bones, which must
not be broken, are buried.
The rite of circumcision, one of the most important of the “five
foundations” of Islam, is performed between the third and eighth
years. The barber operates, and in the case of the rich the event is
celebrated by a feast lasting two or three days, at which the boy
receives presents including hard-boiled eggs, with which he plays a
game by knocking them together.
Children of both sexes are sent to school very young, the idea being
that they will gradually pick up their letters. Education in Kashgar
merely consists of learning by heart a chapter of the Koran and its
Turki equivalent. The letters are taught, penmanship is encouraged,
and lessons are given in the forms of prayer and of ablution.
Geography, history (as distinct from legend), mathematics and
foreign languages are utterly neglected, and the girls leave school at
about ten and most of the boys a year or two later. The teachers are
narrow-minded bigots, and the parents are content to have it so, with
the result that there is not much progress in Kashgar.
We visited the chief boys’ school in Kashgar, where the master bade
his favourite pupils recite passages from the Koran. This they did in
a lugubrious sing-song, swaying backwards and forwards as if in
pain. The pedagogue and his scholars were then photographed,
holding imposing leather-bound and silver-embossed books, which
on enquiry proved to be commentaries on the Koran.
A KASHGAR SCHOOL.
Page 316.
The visitor places his verses secretly in the house and then
decamps. If the owner of the house catches him he beats him, paints
his face like a girl and leads him through the streets calling out, “This
is the punishment for the man who throws snow”; and the visitor is
then bound to give an entertainment. But if the owner of the house
does not catch the visitor, he himself must prepare a banquet. If he
fails to do so within a week, bulrushes are tied on the top of his door,
and if this hint is not sufficient, the bier from the cemetery is placed
outside his house.
Owing to Chinese influence, there is no Moslem country where
respect for parents and for superiors is so strong as in Kashgar.
During the lives of the parents they are never referred to by name by
their children, but are always addressed as “My Lord.” A son will
never sit in the presence of his father without special permission, but
will stand with the head bowed and hands folded in token of humility.
He would never dream of retiring to sleep before his father, nor of
smoking in his presence. To superiors deference is shown by
dismounting from horseback, and by always prefacing an answer
with taksir or “fault,” which has come to be the equivalent of our “Sir.”
Upon receipt of a robe of honour, the recipient bows low, sweeping
the arms in a circle to stroke the beard. Women courtesy by bowing
low with folded hands.
The Kashgaris have few games, but kite-flying, an elementary form
of rounders, pitch-and-toss into a hole with walnuts or coins, and a
kind of tip-cat are favourite amusements. Grown-up men indulge in
ram-fighting and partridge-fighting, heavy bets being made on the
contests.
Music is extremely popular, the Kashgar peasants being distinctly
musical, and their refrains, sung in unison on returning from work,
are pleasing to the European ear. The usual instruments are the
tambourine, the mandoline and the four-stringed rubab. In Kashgar
dancing is regarded as improper, and is indulged in only by
professional women or boys; but in the Khotan oasis, among the
Dulanis of Merket, the Sarikolis and the Kirghiz, men and women
dance together at weddings. At entertainments the men and women
sit on opposite sides and, when the music commences, a woman
rises and places a handkerchief in front of a man, who thereupon
rises also, sings a song and returns the handkerchief. This is done
by all present, and men and women then dance together.
During my stay in Chinese Turkestan I sought for any custom which
might be a survival from the days of the Nestorian Christians. One
such is that horse-dealers, when a bargain is not concluded, make
the sign of the cross on the horse to avert the evil eye. It is
interesting to note that, owing to Chinese influence, black and dark
grey are the favourite colours for horses, whereas few people care to
buy a roan, whose colour is deemed unlucky.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
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