Sorting Algorithms: An Introduction

What is sorting and why is it important? Essentially, sorting is the process of taking a set of any data (in a data structure) and rearranging the whole set into a certain order. This might seem somewhat hard to grasp, but take, for instance, a standard deck of 52 playing cards. We might want to sort such a set in a particular chosen order. Now, the matter of exactly how we sort this deck of cards comes into question and this is what a sorting algorithm is.

Let’s see a sorting algorithm in action. First, we’ll use the simplest sorting algorithm known as bubble sort. In this algorithm, each value is compared with its adjacent values (the values next to it), to see if that value is in the right or wrong spot (usually checking if that value is greater or less than the next). In the case that it’s in the wrong spot, we simply swap the value with the adjacent value. When we do this iteratively (over and over), and with different reference values, we will eventually achieve a sorted data structure.

To exemplify this, let’s say we have 3 cards, all with values 9, 3, and 5, in that order. We want to get our cards in ascending order. Our sorting algorithm will go as follows:

  • Compare 9 with 3, since it’s greater, we swap 9 and 3. Deck: 3, 9, 5

  • Compare 9 with 5, again, it’s greater, so we will swap 9 and 5. Deck: 3, 5, 9

  • Now, we move onto 3, it’s the first entry and less than 5, so it’s in its correct spot Deck: 3, 5, 9

  • Now we compare 5, 5 is both greater than 3 and less than 9, so it’s in its correct spot. Deck: 3, 5, 9

At first, you might be asking “How does this relate to computer programming?” Well, in programming, we use various data structures to store multiple pieces of data in the same category. When we work with data structures, we always want to make it easy to process and that often comes when it is put in a certain order. For instance, if we wanted to make a program to assist teachers in comparing their student’s test scores, it’d be very helpful to first store the different test scores in an array or list (which are data structures) and put our data from least to greatest. This will make processes, such as setting a grading curve, much easier.

The key takeaway in this article is to know that sorting algorithms are used with data structures to set the data in a particular order, such that the data is easier to work with more efficiently.

Picture Source: growingwithweb.com

Picture Source: growingwithweb.com

Kristofer Santo- CuriouSTEM Staff

Content Director- Computer Programming

Previous
Previous

The Brain Activity when you Sleep

Next
Next

What is Impulse?