Friday 11 July 2014

Sort and search algorithms using C# Part one

Welcome to the introduction of searching and sorting algorithms in C# part one. This will be a two part series. The first part will introduce and talk about six sorting algorithms and one searching algorithm. These algorithms will be built using a single data type, an int. In part two, I will modify the algorithms from part one to allow more data types. The contents in each part will not attempt to teach C# as that information is left for the reader to investigate. Each algorithm will be posted once every week.



Most of what what a computer is expected to do is searching and sorting. Information found on search engines use searching algorithms, looking for a word in a text editor uses searching. Sorting is performed quite extensively and sometimes they are performed but not noticed. A list of music you have may be sorted in various ways such as alphabetical order of album name, or artist name, or even song name. Looking for a file in a directory you might be tempted to use one of its ordering functions. There are many things we do and some we don't even notice where powerful algorithms are working hard to provide you with a great user experience and of course to do it in the fastest way possible.

So why have I written this blog post when there are so many books and websites that already feature all of the algorithms I will present. The answer is that I will write it in a way that would make every attempt to produce understandable instructions and also provide complete example codes. Many of the algorithms follow a paradigm that will be immediately obvious if you have already done searches for how to write these algorithms. Furthermore this is a technology blog so it really wouldn't be complete without some sort of searching and sorting algorithm present.

The index below will provide what is to be expected in the coming weeks as well as serve as a landing page to jump straight to the appropriate algorithm. These links will be  updated as new algorithms are added to part one.

Algorithms covered:
  1. Bubble Sort.
  2. Selection Sort.
  3. Insertion Sort.
  4. Quick Sort.
  5. Merge Sort.
  6. Heap Sort.
  7. Binary Search.
 I will begin right now with a method that we will use for all the sorting algorithms. It is a trivial method and ordinarily does not need to be mentioned, however for completeness, with care for any learner programmers, and to get things started, I will show the code for the "Swap" method.

The swap method takes a reference to an array of ints, and two indices 'i' and 'j' of the elements to swap. Inside the method element at index i is stored in a temporary storage variable and this element in the array is overwritten by the element at index j. Finally the element at index j is overwritten by the int we stored in the temporary variable.

Next: Bubble Sort.

No comments :

Post a Comment