Book Image

C# Data Structures and Algorithms

By : Marcin Jamro
Book Image

C# Data Structures and Algorithms

By: Marcin Jamro

Overview of this book

Data structures allow organizing data efficiently. They are critical to various problems and their suitable implementation can provide a complete solution that acts like reusable code. In this book, you will learn how to use various data structures while developing in the C# language as well as how to implement some of the most common algorithms used with such data structures. At the beginning, you will get to know arrays, lists, dictionaries, and sets together with real-world examples of your application. Then, you will learn how to create and use stacks and queues. In the following part of the book, the more complex data structures will be introduced, namely trees and graphs, together with some algorithms for searching the shortest path in a graph. We will also discuss how to organize the code in a manageable, consistent, and extendable way. By the end of the book,you will learn how to build components that are easy to understand, debug, and use in different applications.
Table of Contents (14 chapters)


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!

Are you interested in knowing the influence of choosing a suitable data structure on the performance of your application? Do you want to know how you can increase the quality and performance of your solution by choosing the right data structure and accompanying algorithm? Are you curious about real-world scenarios where these data structures can be applied? If you answer positively to any of these questions, let's start reading this book to learn about various data structures and algorithms that you can use while developing applications in C#.

Arrays, lists, stacks, queues, dictionaries, hash sets, trees, heaps, and graphs, as well as accompanying algorithms—a broad range of subjects awaits you in the next pages! Let's start the adventure and take the first step toward your mastery of data structures and algorithms, which hopefully will have a positive effect on your projects and on your career as a software developer!

Who this book is for

This book is aimed at developers who would like to learn about the data structures and algorithms that can be used in C# in various kinds of applications, including web and mobile solutions. The topics presented here are suitable for programmers with various levels of experience, and even beginners will find interesting content. However, having at least a basic knowledge of the C# programming language, such as about object-oriented programming, will be an added advantage.

To easily understand the content, the book is equipped with many illustrations and examples. What's more, the source code for the accompanying projects is attached to the chapters. Thus, you can easily run example applications and debug them without writing the code on your own.

It is worth mentioning that the code can be simplified, and it can differ from the best practices. What's more, the examples can have significantly limited, or even no, security checks and functionalities. Before publishing your application using the content presented in the book, the application should be thoroughly tested to ensure that it works correctly in various circumstances, such as in the scenario of passing incorrect data.

What this book covers

Chapter 1, Getting Started, explains the very important role of using 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.

Chapter 3, Stacks and Queues, explains how to use two variants of limited access data structures, namely stacks and queues, including priority queues. The chapter shows how to perform push and pop operations on a stack, and also describes the enqueue and dequeue operations in the case of a queue. To aid your understanding of these topics, a few examples are presented, including the Tower of Hanoi game and an application that simulates a call center with multiple consultants and callers.

Chapter 4, Dictionaries and Sets, focuses on data structures related to dictionaries and sets, which make it possible to map keys to values, perform fast lookup, and carry out various operations on sets. The chapter introduces you to both nongeneric and generic variants of a hash table, the sorted dictionary, and the high-performance solution to set operations, together with the concept of the "sorted" set.

Chapter 5, Variants of Trees, describes a few tree-related topics. It 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.

Chapter 6, Exploring Graphs, contains a lot of information about graphs, starting with an explanation of their basic concepts, including nodes and a few variants of edges. The implementation of a graph in C# is also covered. The chapter introduces you to two modes of graph traversal, namely depth-first and breadth-first search. Then, it presents the subject of minimum spanning trees using Kruskal's and Prim's algorithms, the node coloring problem, and the solution to finding the shortest path in a graph using Dijkstra's algorithm.

Chapter 7, Summary, is the conclusion to all the knowledge acquired from the previous chapters. It shows a brief classification of data structures, dividing them into two groups, namely linear and nonlinear. Finally, the chapter talks about the diversity of the applications of various data structures.

To get the most out of this book

The book is aimed at programmers with various experience. However, beginners will also find some interesting content. Nevertheless, at least a basic knowledge of C#, such as about object-oriented programming, will be an added advantage.

Download the example code files

You can download the example code files for this book from your account at If you purchased this book elsewhere, you can visit and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at 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:

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, folder names, filenames, file extensions, pathnames, dummy URLs, and user input. Here is an example: "The class contains three properties (namely Id, Name, and Role), as well as two constructors."

A block of code is set as follows:

int[,] numbers = new int[,] = 
    { 9, 5, -9 }, 
    { -11, 4, 0 }, 
    { 6, 115, 3 }, 
    { -12, -9, 71 }, 
    { 1, -6, -1 } 

Any command-line input or output is written as follows:

    Enter the number: 10.5The average value: 10.5 (...)Enter the number: 1.5The average value: 4.875

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "When the message Installation succeeded! is shown, click on the Launch button to start the IDE."


Warnings or important notes appear like this.


Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit, selecting your book, clicking on the Errata Submission Form link, and entering the details.

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 [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit


Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit