Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Programming Language> C# Data Structures and Algorithms
C# Data Structures and Algorithms
C# Data Structures and Algorithms

C# Data Structures and Algorithms: Harness the power of C# to build a diverse range of efficient applications , Second Edition

Arrow left icon
Profile Icon Marcin Jamro
Arrow right icon
$35.98$39.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.1(26 Ratings)
eBookFeb 2024372 pages2nd Edition
eBook
$35.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$35.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

C# Data Structures and Algorithms

Introduction to Algorithms

While reading the first chapter of this book, you learned about various data types. Now, it is high time to introduce the topic of algorithms. In this chapter, you will take a look at theirdefinition, as well as some real-worldexamples,notations, andtypes. As you should take care of the performance of your applications, the subject of computational complexity of the algorithms, including time complexity, will also be presentedand explained.

First, it is worth mentioning that the topic of algorithms is very broad and complex. You can easily find a lot of scientific publications about them on the internet, published by researchers from all over the world. The number of algorithms is enormous and it is almost impossible to even remember the names of all the commonly used ones. Of course, some algorithms are simple to understand and implement, while others are extremely complex and almost impossible to understand without deep knowledge of algorithmics, mathematics, and other dedicated field of science. There are also various classifications of algorithms by different key features, and there are a lot of types, including recursive, greedy, divide-and-conquer, back-tracking, and heuristic. However, for various algorithms, you can specify the computational complexity by stating how much time or space they require to operate with the increasing size of aprocessed input.

Does this sound overwhelming, complicated, and difficult? Don’t worry. In this chapter, I will try to introduce the topic of algorithms in a way that everyone can understand, not only mathematicians or other scientists. For this reason, in this chapter, you will find some simplifications to make this topic simpler and easier to follow. However, the aim is to introduce you to this topic andmake you interested in algorithms, not create another research publication or book with a lot of formal definitions and formulas. Are you ready? Let’sget started!

In this chapter, we will cover thefollowing topics:

  • Whatare algorithms?
  • Notations foralgorithm representation
  • Typesof algorithms
  • Computational complexity

What are algorithms?

Did you knowyou typically use algorithms every day and that you are already an author of some algorithms, even without writing any lines of code or drawing a diagram? If this sounds impossible, give me a few minutes and read this section to get to know how isit possible.

Definition

First, you needto know what analgorithm is. It is awell-defined solution for solving a particular problem or performing a computation. It is an ordered list of preciseinstructions that are performed in a given order and take a well-definedinput into account (if any) to produce a well-definedoutput, asshown here:

Figure 2.1 – Illustration of an algorithm

Figure 2.1 – Illustration of an algorithm

To be more precise,an algorithm should contain a finite sequence of unambiguous instructions, which provides you with an effective and efficient way of solving the problem. Of course, an algorithm can containconditional expressions,loops,orrecursion.

Where can you find more information?

If you are interested in the topic of algorithms, you can find a lot of detailed information about them in many books, includingIntroduction to Algorithms, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Of course, there are also many resources available online, such asGeeksForGeeks (https://www.geeksforgeeks.org),The Algorithms (https://the-algorithms.com), andAlgorithms, 4th Edition, by Robert Sedgewick and Kevin Wayne (https://algs4.cs.princeton.edu). A huge number of resources is also available if you browse theAlgorithms topic on GitHub (https://github.com/topics/algorithms). I strongly encourage you to search for various resources, either in books or over the internet, and continue learning about algorithms when you’ve finished readingthis book.

Real-world examples

With the definitionof algorithms under your belt, you might be thinking, “Come on – inputs, outputs, instructions… where I can find them?” The answer turns out to be much simpler than you might expect because you can find such items almost everywhere, allthe time!

Let’s start with asimple morning routine. First, you wake up and take a look at your phone. If there are any notifications, you go through them and reply to urgent messages. For any unurgent items, you postpone them. Then, you go to the bathroom. If it is occupied, you wait until it is free, telling the person inside to hurry up. As soon as you are in the bathroom, you take a shower and brush your teeth. Finally, you choose suitable clothes according to the current weather and temperature. Surprise! Your morning routine is an algorithm. You can describe it as a set of instructions, which has some inputs, such as notifications and the current temperature, as well as outputs, such as chosen clothes. What’s more, some of the instructions are conditional, such as only replying to urgent messages. Others can be executed in a loop, such as waiting until the bathroomis vacant.

The preceding morning routine also contains other algorithms, such as those forunlocking a smartphone using face recognition. It is an algorithm-based mechanism that you can use to ensure that only you can unlock your phone. What’s more, evenorganizing notifications on your phone is the result of an algorithm that takes into account notifications as input, arranges them into groups, and sorts them suitably before presenting themto you.

At this point, you are dressed up and ready for a healthy and yummy breakfast. Imagine that you want toprepare scrambled eggs using your grandma’s secret recipe. You need some ingredients, namely three eggs, salt, and pepper. As a result, you will have created an amazing dish for your perfect breakfast. First, you crack the eggs into a bowl and whisk them with a pinch of salt and pepper. Then, you melt butter in a non-stick skillet over medium-low heat. Next, you pour the egg mixture into the skillet and keep the eggs movinguntil there is no liquid egg. With that, your breakfast is ready. However, what is it if not a well-written and organized algorithm with a precise input andyummy output?

After breakfast, you need to go to work. So, you jump into your car and launch a navigation app on your smartphone to seethe fastest route to work while taking the current trafficinto account. This task is performed by complicated algorithms that can even involveartificial intelligence (AI), together with a computer-understandable representation of routes that use specialized data structures, as well as data obtained from other users. When combined, this forms traffic data. As you can see, the algorithm takes the complex input and performs various calculations to present you with an ordered list of route directions – for example, go to route A4, turn right to route S19, and follow this route until you reachyour destination.

While at work, you need to prepare documents for your accountant, so you need to gather documents from colleagues, print some of them from emails, and thensort all invoices by numbers. How do you perform sorting? You take the first document from the stack and put it on the table. Then, you take the second document from the unsorted stack and put it either above, if the number is smaller than the first invoice, or below the previous one. Then, you take the third invoice and find a suitable place for it in the ordered stack. You perform this operation until there are no documents in the unsorted stack. Wow, another algorithm? Exactly! This is one ofsorting algorithms. You'll learn about them in thenext chapter.

It’s time for a break at work! You launch your favorite social app andreceive suggestions for new friends. However, how are they found and proposed to you? Yes, you’re right – this is another algorithm that takes data from your profile and your activities, as wellas the data of available users, as input, and returns a collection of best-suited suggestions for you. It can use many complex and advanced techniques, such asmachine learning (ML) algorithms, which can learn and take your previous reactions into account. Just think for a second about the data structures that can be used in such cases. How you can organize your relationships with friends and how can you find out how many other people are between you and your favorite actor from Hollywood? It would be great to know that your friend knows Mary, who knows Adam, who is a friend of your idol, wouldn’t it? Such a task can be accomplished usingsome graph-based structures, as you will see later inthis book.

Will you learn about AI algorithms in this book?

Unfortunately, no. Due to the limited number of pages, various algorithms related to AI are not included in this book. However, note that it is a very interesting topic that involves manyconcepts, such asML anddeep learning (DL), which are used in many applications, including recommendation systems, speech-to-text, searchingover extremely high amounts of data (the concept ofbig data), generating textual and graphical content, as well as controlling self-driving cars. To achieve these goals, a lot of interesting algorithms are used. I strongly encourage you to take a look at this topic on your own or choose one of Packt’s books that focuses onAI-related topics.

Are these examples enough? If not, just think aboutchoosing a movie in a cinema for the evening while considering the AI-based suggestions of movies with geolocation-based data of cinemas, orsetting a clock alarm depending on your plan for the next day. As you can see,algorithms are everywhere and all of us use them, even if we do notrealize it.

So, if algorithms are so common and so useful, why don’t we benefit from the huge collection of ones that are available or even write our own algorithms? There are still some problems that need to be solved using algorithms. I, as the author of this book, am keeping my fingers crossed for you tosolve them!

Notations for algorithm representation

In theprevious section, algorithms were presented in English. However, this is not the only way of specifying and documenting an algorithm. In this section, you will learn about four notations for algorithm representation, namelynatural language,flowchart, pseudocode, andprogramming language.

To make thistask easier to understand, you will specify the algorithm for calculating anarithmetic mean in all of these notations. As a reminder, the mean can be calculated using thefollowing formula:

Figure 2.2 – Formula for calculating an arithmetic mean

Figure 2.2 – Formula for calculating an arithmetic mean

As youcan see, two inputs are used, namely the provided numbers (a) and the total number of elements (n). If no numbers are provided,null is returned, indicating that no mean is available. Otherwise, you sum the numbers and divide them by the total number of elements to getthe result.

Natural language

First, let’s specify the algorithm using a natural language. It is a very easy way of providinginformation about algorithms, but it can be ambiguous and unclear. So, let’s describe our algorithm inthis way:

The algorithm reads the input, which represents the total number of elements from which an arithmetic mean will be calculated. If the entered number is equal to 0, the algorithm should return null. Otherwise, it should read the numbers in the amount equal to the expected total count. Finally, it should return the result as the sum of numbers divided bytheir count.

Quite simple and understandable, isn’t it? You can use this notation for simple algorithms, but it can be useless for complex and advanced algorithms. Of course, some descriptions in the natural language are often useful, regardless of the complexity of an algorithm. They can give you a brief understanding of what the aim of the algorithm is, how it works, and what aspects should be taken into account while you’re analyzing or implementingthe algorithm.

Flowchart

Another wayof presenting an algorithm is via aflowchart. A flowchartuses a set of graphical elements to prepare a diagram that specifies the algorithm’s operation. Some of the available symbols areas follows:

Figure 2.3 – The available symbols while designing a flowchart

Figure 2.3 – The available symbols while designing a flowchart

The algorithm should contain theentry point and one or moreexit points. It can also contain other blocks, includingoperation,input,output, orcondition. The following blocks are connected witharrows that specify the order of execution. You can alsodrawloops.

Let’s take a look at a flowchart for calculating thearithmetic mean:

Figure 2.4 – Flowchart for calculating the arithmetic mean

Figure 2.4 – Flowchart for calculating the arithmetic mean

The execution starts in theSTART block. Then, we assign0 as a value of thesum variable, which stores the sum of all the entered numbers. Next, we read a value from the input andstore it as a value of then variable. This is the total number of elements used to calculate the arithmetic mean. Next, we checkwhethern is equal to0. If so, theYES branch is chosen,null is returned to the output, and the execution stops. Ifn is not equal to0, theNO branch is chosen and we assign0 as a value of thei variable. It stores the number of elements already read from the input. Next, we read the number from the input and save it as a value of thea variable. The following operation block increasessum by the value ofa, as well as increments the valueofi.

The next block is a conditional one that checks whetheri is not equal ton, which means that the required number of elements is not read from the input yet. Ifi is equal ton, theNO branch is chosen and a value of theresult variable is set to a result of a division ofsum byn. Then, theresult variable is returned and the execution stops. An interesting construction is used when the conditional expression evaluates totrue, which means that we need to read another input. Then, the loop is used and the execution comes back just before the input block for readinga. Thus, we can execute some operations multiple times, until the conditionis met.

As you can see, a flowchart is a diagram that makes it possible to specify a way of algorithm operation in a more precise way than using natural language. It is an interesting option for simple algorithms, but it can be quite cumbersome in the case of advanced and complex ones, where it is impossible to present the whole operation within a diagram of a reasonablysmall size.

Pseudocode

The nextnotation we’ll look at ispseudocode. It allows you to specify algorithmsin another way, which is a bit similar to the code written in a programming language. Here, we use the English language to define inputs and outputs, as well as to present a set of instructions clearly and concisely, but without the syntax of anyprogramming language.

Here’s some example pseudocode for calculating thearithmetic mean:

INPUT:n – total number of elements used for mean calculation.a – the following numbers entered by a user.OUTPUT:result - arithmetic mean of the entered numbers.INSTRUCTIONS:sum <- 0read nif n = 0 then   return nullendifi <- 0do   read a   sum <- sum + a   i <- i + 1while i <> nresult <- sum / nreturn result

As youcan see, the pseudocode provides uswith a syntax that is easy to understand and follow, as well as quite close to a programming language. For this reason, it is a precise way of algorithm presentation and documentation that can be later used to transform it into a set of instructions in our chosenprogramming language.

Programming language

Now, let’s look at the last form of algorithm notation:programming language. It is very precise, can be compiled and run. Thus, we can see the result of its operation and check it using a set of test cases. Of course, wecan implement an algorithm in any programming language. However, in this book, you will see only examples in theC# language.

Let’s take a look at the implementation of the meancalculation algorithm:

double sum = 0;Console.Write("n = ");int.TryParse(Console.ReadLine(), out int n);if (n == 0) { Console.WriteLine("No result."); }int i = 0;do{    Console.Write("a = ");    double.TryParse(Console.ReadLine(), out double a);    sum += a;    i++;}while (i != n);double result = sum / n;Console.WriteLine($"Result: {result:F2}");

The preceding code contains anif conditional statement and ado-while loop.

If we run the application, we need to enter the number of elements from which we would like to calculate the arithmetic mean. Then, we will be asked to enter the numbern times. When the number of provided elements is equal to the expected value, the result is calculated and presented in the console,as follows:

n = 3a = 1a = 5a = 10Result: 5.33

That’s all! Now, you know what algorithms are, where you can find them in yourdaily life, as well as how to represent algorithmsusing natural language, flowcharts, pseudocode, and programming languages. With this knowledge, let’s proceed to learn about different types of algorithms, including recursive andheuristic algorithms.

Types of algorithms

As mentioned previously, algorithms are almost everywhere, and even intuitively, you use them eachday while solving various tasks. There is an enormous amount of algorithms and a lot of their types, chosen according to different criteria. To simplify this topic, only a few types will be presented here, chosen from different classifications, to show you a variety and encourage you to learn more about them on your own. It is also quite common that the same algorithm is classified into afew groups.

Recursive algorithms

First, let’stake a look atrecursive algorithms, whichare strictly connected with the idea ofrecursion and arethe opposite ofiterative algorithms. What does this mean?An algorithm is recursive if it calls itself to solve smaller subproblems of the original problem. The algorithm calls itself multiple times until thebase conditionis met.

This technique provides you with a powerful solution for solving problems, can limit the amount of code, and can be easy to understand and maintain. However, recursion has some drawbacksrelated to performance or the requirementfor more space in the stack’s memory, which could lead to stack overflow problems. Fortunately, you can prevent some of these issues usingdynamic programming, an optimization technique thatsupports recursion.

Recursion can be used in several algorithms, includingthe following:

  • Sorting an array with themerge sort andquicksort algorithms, which are implemented and presented in detail inChapter 3,Arraysand Sorting
  • Solving theTowers of Hanoi game, as depicted inChapter 5,Stacksand Queues
  • Traversing a tree, as described inChapter 7,Variantsof Trees
  • Getting a number from theFibonacci series, as shown inChapter 9,Seein Action
  • Generating fractals, as shown inChapter 9,Seein Action
  • Calculating afactorial (n!)
  • Getting thegreatest common divisor of two numbers using theEuclidean algorithm
  • Traversing the filesystem with directoriesand subdirectories

Divide and conquer algorithms

Anothergroup of algorithms is nameddivide and conquer. It isrelated to thealgorithmic paradigm of solving a problem by breaking it down into smaller subproblems (the “divide” step), calling them recursively until they are simple enough to be solved directly (“conquer”), and combining the results of subproblems to get the final result (“combine”). This approach has many advantages, also taken from the pros of recursion, including ease of implementation, understanding, and maintenance. By dividing the problem into many subproblems, it supportsparallel computing, whichcan lead to performance improvements. Unfortunately, this paradigm also has some disadvantages, including the necessity for a proper base case definition to terminate the execution of the algorithm. Performance issues, similar as in the case of recursive algorithms, can existas well.

Divide andconquer is a popular approach for solvingvarious algorithmic problems and you can see its implementations in a broad rangeof applications:

  • Sorting an array with themerge sort andquicksort algorithms, which are implemented and presented in detail inChapter 3,Arraysand Sorting
  • Finding the closest pair of points located on the two-dimensional surface, which will be presented inChapter 9,Seein Action
  • Calculating thepower ofa number
  • Finding theminimum and maximum values inan array
  • Calculating thefastFourier transform
  • Multiplying large numbers usingKaratsuba’s algorithm

Back-tracking algorithms

Next, we’llcoverback-tracking algorithms.They are used for solving problems that consist of a sequence of decisions, each depending on the decisions that have already been taken, incrementally building the solution. When you realize that the decisions that have been taken do not provide the correct solution, youbacktrack. Of course, you cansupport this approach with recursion to try various variants and therefore find a suitable solution, ifone exists.

You can use this approach for many tasks, includingthe following:

  • Solving therat in a maze problem, as shown inChapter 9,Seein Action
  • SolvingSudoku, as shown inChapter 9,Seein Action
  • Solvingcrosswords by entering letters intoempty spaces
  • Solving theeight queensproblem of placing eight queens on a chessboard and notallowing them to attackeach other
  • Solving theknight’s tour, where you place a knight on the first block on a chessboardand move it so that it visits all blocksexactly once
  • Generatinggray codes to create bit patterns where the following ones differ by onebit only
  • Solving them-coloring problem forgraph-related topics

Greedy algorithms

Now thatwe’ve covered the recursive, divide-and-conquer, and back-trackingalgorithms, it’s high time to present another type, namely greedy algorithms.Agreedy algorithm builds the solution piece by piece by choosing the best option in each step, not concerned about the overall solution, and being short-sighted in its operation. For this reason, there is no guarantee that the final result is optimal. However, in many scenarios, using the local optimal solutions can lead to global optimal solutions or can begood enough.

Here aresome examples:

  • Finding the shortest path in a graph usingDijkstra’s algorithm, as shown and explained in detail inChapter 8,Exploring Graphs
  • Calculating the minimum spanning tree in a graph withKruskal’s algorithm andPrim’s algorithm, as shown inChapter 8,Exploring Graphs
  • Solving theminimum coin change problem, as explained inChapter 9,Seein Action
  • The greedy approach toHuffman coding indatacompression algorithms
  • Load balancing andnetwork routing

Heuristic algorithms

Now, it’s timeto add more “magic” to your algorithms via heuristics!Aheuristic algorithm calculates a near-optimal solution for an optimization problem and is especially useful for scenarios when the exact methods are not available or are too slow. Thus, you can see a significant speed boost, but with a decreased accuracy of the result. Such an approach is popular andadequate for solving various real-world problems, often complex and big, and is applied in many different fields of science, even thoseregarding bioinformatics.

Heuristicalgorithms have many applicationsand subtypes:

  • Genetic algorithms, which areadaptive heuristic search algorithms, andcan be used to guess the title of this book, as depicted inChapter 9,Seein Action
  • Solvingvehicle routing problems and thetraveling salesman problem with theTabuSearch algorithm
  • Solving theKnapsack problem, where you need to choose items of the maximum total value to be packed within themass limit
  • Filtering andprocessing signals
  • Detecting viruses

Dynamic programming

Since we’retalking about various types of algorithms, it isworth mentioningdynamic programming. It is atechnique that optimizes recursive algorithms by limiting the necessity of computing the same result multiple times. This technique can be used in one oftwo approaches:

  • Thetop-down approach, whichusesmemoization to savethe results of subproblems. Therefore, thealgorithm can use the value from the cache and does not need to recalculate the same results multiple times or does not need to call the method with the same parametersmultiple times.
  • Thebottom-up approach, which usestabulation toreplace recursionwith iteration. It limits the numberof function calls and problems regardingstack overflow.

Both ofthese approaches can significantly decrease the time complexity and increase performance, and therefore speed upyour algorithm. Every time you use recursion, it is a good idea to try to optimize it using dynamic programming. If you want to learn how to optimize calculating a number from theFibonacci series, go toChapter 9,Seein Action.

You can also use dynamic programming to find theshortest path between all pairs of vertices in a graph by using theFloyd-Warshall algorithm, as well as inDijkstra’s algorithm. Another application is for solving theTower of Hanoi mathematical game. Possibilities are even broader and you can also apply it toartificialneural networks.

Brute-force algorithms

While we’representing various types of algorithms, we should also consider brute-force algorithms.Abrute-force algorithm is a general solution for solving a problem by checking all possible options and choosing the best one. It is an approach that can have huge time complexity and its operationcan take a lot of time, so it can be useless in real-world scenarios. However, a brute-force algorithm is often the first choice when you need to solve some algorithmic problem. There’s nothing bad in doing this as you can learn more about the domain of the problem you wish to solve and see some results for simpler cases. Nevertheless, while developing an algorithm, it is a good idea to enhance it significantly by usingother paradigms.

Here are someexamples of where you can usebrute-force algorithms:

  • Guessing a password, where you check each possible password one after the other, as presented inChapter 9,Seein Action
  • Finding the minimum value in an unsorted array, where you need to iterate through all items as there is no relationship between values inthe array
  • Finding the best possible plan for a day, placing various tasks between meetings, andtrying to organize it in a way that you can start working late andending early
  • Solving thetravelingsalesman problem

After introducing a few types of algorithms, you can see that some of them provide you with a faster solution while others can have huge time complexity. But what does this mean? You will learn about computational complexity, especially time complexity, in thenext section.

Computational complexity

In this final section, let’s take a look at thecomputational complexity of algorithms, focusingon bothtime complexity andspace complexity. Why is this so important? Because it can decide whether your algorithm can be used in real-world scenarios. As an example, which of the following doyou prefer?

  • (A) Absolutely the best route directions to work, but you receive them after an hour, when you are alreadyat work.
  • (B) Good enough route directions to work, but you receive them within a few seconds, a moment after you enteryour car.

I am sure that you choseBme too!

Time complexity

First, let’sfocus ontime complexity, whichindicatesthe amount of time necessary to run an algorithm as a function of the input length, namelyn. You can specifyit usingasymptotic analysis. This includesBig-O notation, which isused to indicatehow much time the algorithm will take with the increasing size ofthe input.

For example, if you search for the minimum value in an unsorted array of sizen, you need to visit all elements so that the maximum number of operations is equal ton, which is written asO(n). If the algorithm iterates through each item in a two-dimensional array of sizen x n, the time complexity isO(n*n), so itisO(n2).

There arevarious time complexities, includingthe onespresented here:

Figure 2.5 – Illustration of time complexities

Figure 2.5 – Illustration of time complexities

The first isO(1) and is named theconstant time. It indicates an algorithm whose execution time doesnot depend on the input size. The exemplary operations consistent with theO(1) constraint are getting ani-th element from an array, checking whether a hash set contains a given value, or checking whether a number is evenor odd.

The next timecomplexity shown here isO(log n), which is named thelogarithmic time. In this case, the execution time is not constant, but it increases slower than in the linear approach. A well-known example of theO(log n) constraint is the problem of finding an item in a sorted array withbinary search.

The third case isO(n) and isnamed thelinear time. Here, the execution time increases linearly with the input length. You can take an algorithm for finding the minimum or maximum value in an unordered list or simply finding a given value in an unordered list as examples of theO(n) constraint.

The last time complexityshown here is thepolynomial time, which isO(nm), so itcan beO(n2) (quadratic time),O(n3) (cubic time), and soon. In this case, the execution time increases much faster than in the case of the linear constraint. It can involve solutions that use nested loops. Examples include the bubble sort, insertion sort, and selection sort algorithms. We'llcoverthese inChapter 3,Arraysand Sorting.

Ofcourse, thereare evenmore time complexitiesavailable, amongwhichyou will finddouble logarithmic time,polylogarithmic time,fractional power time,linearithmic time,exponential time, andfactorial time.

Space complexity

Similar totime complexity, you can specify thespace complexity usingasymptotic analysis and the Big-O notation. Space complexity indicateshow much memory is necessary to run the algorithm with the increasinglength of input. You can use similar indicators, such asO(1),O(n),orO(n2).

Where can you find more information?

In this chapter, only a very brief introduction to the subject of algorithms was presented. I strongly encourage you to try to broaden your knowledge regarding algorithms on your own. It is an extremely interesting and challenging topic. For example, you can learn more about various types of algorithms athttps://www.techtarget.com/whatis/definition/algorithm and athttps://www.geeksforgeeks.org/most-important-type-of-algorithms/, while about the computational complexity athttps://en.wikipedia.org/wiki/Computational_complexity. I am keeping my fingers crossed for you successwith algorithms!

Summary

You’ve just completed the second chapter of this book, which was all about data structures and algorithms in the C# language. This time, we focused on algorithms and indicated their crucial role in the development of various applications, regardless oftheir types.

First, you learnedwhat an algorithm is andwhere you can find algorithms in your daily life. As you saw, algorithms are almost everywhere and you use and design them without evenknowing it.

Then, you learned aboutnotations for algorithm representation. There, you learned how to specify algorithms in a few ways, namely in a natural language, using a flowchart, via pseudocode, or directly in aprogramming language.

Next, you learnedabout a few different types of algorithms, starting with the recursive algorithms that call themselves to solve smaller subproblems. Then, you learned aboutdivide and conquer algorithms, which divide the problem into three stages, namely divide, conquer, and combine. Next, you learned aboutback-tracking algorithms, which allow you to solve problems consisting of a sequence of decisions, each depending on a decision that’s already been taken, together with the backtrack option if the decisions do not provide a correct solution. Then, you learned aboutgreedy algorithms, which choose the best option in each step of their operation while not being concerned about the overall solution. Another group you learned about washeuristic algorithms for finding near-optimal solutions. Then, you learned that you can optimize recursive algorithms usingdynamic programming and its top-down and bottom-up approaches. Finally, you learned aboutbrute-force algorithms.

The final part of this chapter looked atcomputational complexity in terms of time and space complexity. Asymptotic analysis, together with Big-O notation,was presented.

In the next chapter, we’ll coverarrays and varioussorting algorithms. Are you ready to continue your adventure with data structures and algorithms in the C# language? If so,let’s go!

Left arrow icon

Page1 of 6

Right arrow icon
Download code iconDownload Code

Key benefits

  • Master lists, stacks, queues, dictionaries, sets, and trees, among other data structures
  • Delve into effective design and implementation techniques to meet your software requirements
  • Visualize data structures and algorithms through illustrations for a clearer understanding of their analysis
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Building your own applications is exciting but challenging, especially when tackling complex problems tied to advanced data structures and algorithms. This endeavor demands profound knowledge of the programming language as well as data structures and algorithms. C# Data Structures and Algorithms, armed with critical knowledge from an entrepreneur, author, industry expert, and seasoned developer with significant international experience, offers just that to C# developers.Starting with an introduction to algorithms, this book gradually immerses you in the world of arrays, lists, stacks, queues, dictionaries, and sets. Real-world examples, enriched with code snippets and illustrations, provide a practical understanding of these concepts. You’ll also learn how to sort arrays using various algorithms, setting a solid foundation for your programming expertise. As you progress, you’ll venture into more complex data structures – trees and graphs – and discover algorithms for tasks such as determining the shortest path in a graph before advancing to see various algorithms in action, such as solving Sudoku.By the end of this book, you’ll be able to use the C# language to build algorithmic components that are not only easy to understand and debug but also seamlessly applicable in various apps, spanning web and mobile platforms.

Who is this book for?

This book is for developers looking to learn data structures and algorithms in C#. While basic programming skills and C# knowledge is useful, beginners will find value in the provided code snippets, illustrations, and detailed explanations, enhancing their programming skills. Advanced developers can use this book as a valuable resource for reusable code snippets, instead of writing algorithms from scratch each time.

What you will learn

  • Understand the fundamentals of algorithms and their classification
  • Store data using arrays and lists, and explore various ways to sort arrays
  • Build enhanced applications with stacks, queues, hashtables, dictionaries, and sets
  • Create efficient applications with tree-related algorithms, such as for searching in a binary search tree
  • Boost solution efficiency with graphs, including finding the shortest path in the graph
  • Implement algorithms solving Tower of Hanoi and Sudoku games, generating fractals, and even guessing the title of this book

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Feb 29, 2024
Length:372 pages
Edition :2nd
Language :English
ISBN-13 :9781803238821
Category :
Languages :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Feb 29, 2024
Length:372 pages
Edition :2nd
Language :English
ISBN-13 :9781803238821
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts

Frequently bought together


C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
Read more
Nov 2023828 pages
Full star icon4.4 (74)
eBook
eBook
$42.99$47.99
$59.99
Architecting ASP.NET Core Applications
Architecting ASP.NET Core Applications
Read more
Mar 2024806 pages
Full star icon4.5 (11)
eBook
eBook
$33.99$37.99
$46.99
C# Data Structures and Algorithms
C# Data Structures and Algorithms
Read more
Feb 2024372 pages
Full star icon4.1 (26)
eBook
eBook
$35.98$39.99
$49.99
Stars icon
Total$156.97
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
$59.99
Architecting ASP.NET Core Applications
$46.99
C# Data Structures and Algorithms
$49.99
Total$156.97Stars icon

Table of Contents

12 Chapters
Chapter 1: Data TypesChevron down iconChevron up icon
Chapter 1: Data Types
C# as a programming language
.NET-based console applications
Division of data types
Value types
Reference types
Summary
Chapter 2: Introduction to AlgorithmsChevron down iconChevron up icon
Chapter 2: Introduction to Algorithms
What are algorithms?
Notations for algorithm representation
Types of algorithms
Computational complexity
Summary
Chapter 3: Arrays and SortingChevron down iconChevron up icon
Chapter 3: Arrays and Sorting
Single-dimensional arrays
Multi-dimensional arrays
Jagged arrays
Sorting algorithms
Summary
Chapter 4: Variants of ListsChevron down iconChevron up icon
Chapter 4: Variants of Lists
Simple lists
Sorted lists
Linked lists
List-related interfaces
Summary
Chapter 5: Stacks and QueuesChevron down iconChevron up icon
Chapter 5: Stacks and Queues
Stacks
Queues
Priority queues
Circular queues
Summary
Chapter 6: Dictionaries and SetsChevron down iconChevron up icon
Chapter 6: Dictionaries and Sets
Hash tables
Dictionaries
Sorted dictionaries
Hash sets
“Sorted” sets
Summary
Chapter 7: Variants of TreesChevron down iconChevron up icon
Chapter 7: Variants of Trees
Basic trees
Binary trees
Binary search trees
Self-balancing trees
Tries
Heaps
Summary
Chapter 8: Exploring GraphsChevron down iconChevron up icon
Chapter 8: Exploring Graphs
The concept of graphs
Applications
Representations
Implementation
Traversal
Minimum spanning tree
Coloring
Shortest path
Summary
Chapter 9: See in ActionChevron down iconChevron up icon
Chapter 9: See in Action
The Fibonacci series
Minimum coin change
Closest pair of points
Fractal generation
Rat in a maze
A Sudoku puzzle
Title guess
A password guess
Summary
Chapter 10: ConclusionChevron down iconChevron up icon
Chapter 10: Conclusion
Classification
Arrays
Lists
Stacks
Queues
Dictionaries
Sets
Trees
Graphs
The last word
IndexChevron down iconChevron up icon
Index
Why subscribe?
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
$27.99$31.99
$39.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
$27.99$31.99
$39.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
$35.98$39.99
$49.99
$49.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
$29.99$33.99
$41.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (12)
eBook
eBook
$35.98$39.99
$49.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
$31.99$35.99
$39.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
$74.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
$38.99$43.99
$54.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconFull star iconHalf star icon4.1
(26 Ratings)
5 star38.5%
4 star42.3%
3 star15.4%
2 star0%
1 star3.8%
Filter icon Filter
Top Reviews

Filter reviews by




CAMILO REYESJun 20, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
Code samples were very solid, everything compiles with on warnings on net8.0. The ideas in the book were welcomed and I can see myself applying some of these techniques in a real project.
Feefo Verified reviewFeefo
julio CasalMay 01, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
I was not expecting a lot from this book.But I'm pleased I did not skip it. Here's why:This is the book I wish existed when I was preparing for coding interviews.This book takes each of the key C# data structures and uses them to master most of the algorithms every developer should know.You'll go through algorithms to search and sort arrays and lists, implement trees and tries, traverse graphs efficiently, and much more.But I think 2 key things make this book really stand out:1. It uses a crazy amount of graphs and other visualizations to help you understand every single algorithm and data structure.2. It complements many chapters with practical examples of how to use the data structures and algorithms in real-life scenarios.Also, I didn't even know that we had a PriorityQueue class available in C#, which this book covers extensively.If you are getting ready for coding interviews, you should get this book.I can't recommend it enough.
Amazon Verified reviewAmazon
Amol ChotaliaMar 28, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
Pretty solid for anyone diving into C# or looking to brush up on their data structure skills.The book is filled with examples that are pretty useful.You get real code snippets you can mess around with, which is great whether you're just starting out or you've been at this for a while but need a quick refresher or a new trick or two. Overall, it does a good job at making complex stuff simple and practical.
Amazon Verified reviewAmazon
Romny ArnoldApr 11, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
This was a great way to brush up on Data Structures. Everything from Arrays to Tree variants, with great examples and easily understood explanations. An understanding of C# is greatly encouraged as this book jumps right into Data Types!
Amazon Verified reviewAmazon
Elle EOct 24, 2020
Full star iconFull star iconFull star iconFull star iconFull star icon5
Udemy Verified reviewUdemy
  • Arrow left icon Previous
  • 1
  • 2
  • 3
  • 4
  • 5
  • ...
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
$35.98$39.99
$49.99
$49.99
Event-Driven Architecture in Golang
Event-Driven Architecture in Golang
Read more
Nov 2022384 pages
Full star icon4.9 (11)
eBook
eBook
$35.98$39.99
$49.99
The Python Workshop Second Edition
The Python Workshop Second Edition
Read more
Nov 2022600 pages
Full star icon4.6 (22)
eBook
eBook
$36.99$41.99
$51.99
Template Metaprogramming with C++
Template Metaprogramming with C++
Read more
Aug 2022480 pages
Full star icon4.6 (14)
eBook
eBook
$33.99$37.99
$46.99
Domain-Driven Design with Golang
Domain-Driven Design with Golang
Read more
Dec 2022204 pages
Full star icon4.4 (19)
eBook
eBook
$31.99$35.99
$44.99
Right arrow icon

About the author

Profile icon Marcin Jamro
Marcin Jamro
LinkedIn icon
Marcin Jamro, PhD, DSc (dr hab. inż. Marcin Jamro) is a reliable entrepreneur, a helpful expert, and an experienced developer, with significant international experience. He held the role of CEO at a few technological companies, operated as CTO at companies in various countries, and also worked at Microsoft Corporation in Redmond, USA. Marcin shares his knowledge as an expert in international projects and invests in modern solutions.He is the author of a few books on software engineering, as well as the author of numerous publications. The results of his research were presented and discussed at many scientific conferences. He has MCPD, MCTS, MCP, and CAE certificates. Marcin is a multiple laureate, finalist, and mentor in various competitions. He received the Primus Inter Pares medal and also, a few times, a scholarship for the Minister of Science and Higher Education for scientific achievements.Marcin has significant experience in project development, especially with the C# language and .NET-based technologies. He has performed the role of lead architect on numerous complex software projects, including web and mobile applications, APIs, databases, and integration with external components.
Read more
See other products by Marcin Jamro
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp