Your scrolling text goes here
top of page

An Absolute Beginner’s Guide to Algorithms

The internet heavily relies on Algorithms. From Google to even Tinder, algorithms are stealthily sorting and applying data in the background of most applications. In fact, the TikTok algorithm is what brought me here today, writing this guide in order to help the community enjoy such an interesting field of Computer Science and Math. In this guide, I will explain what algorithms are, how they work, and how to create a low-level algorithm using Python. All of this will be taught under the assumption that you have never coded before, so don’t worry if you aren’t experienced.


Let’s get started!


What is an Algorithm?

An Algorithm (by definition) is “a finite sequence of rigorous instructions, typically used to solve a class of specific problems or to perform a computation. ” To put that in English, it’s an order of operations that can be performed to achieve a certain output, similar to the mathematical rule PEMDAS. For instance, the TikTok algorithm runs in the background and collects your interaction data from the videos you watch. Using your data, the algorithm will correctly identify when you enjoyed a certain genre or type of TikTok, and slowly start putting similar videos on your feed. This algorithm allows TikTok to be catered to you specifically and more enjoyable for you. When exploring the field of algorithms, you will start to realize how math-heavy it is. Software engineers use Calculus to calculate the amount of time an algorithm will take to give an output with varying levels of input. A good algorithm will take less time, and a bad algorithm will take more time. We use math to make sure our algorithms are performing at the highest level.


Picture shows a visualization of an algorithm, via GeeksForGeeks


How Algorithms Work - Example

In this section, I’m going to give a very brief overview of an algorithm. This algorithm that I’m demonstrating is known as a “Sorting Algorithm.” The algorithm will take in a set of data (in our case, numbers) and sort them in a certain order (in our case, least to greatest)

We will use boxes to visualize this operation.


Step 1: What is the Goal?

Our goal is to achieve a box with numbers 1-5 in order





Step 2: What is our Input?

Our input is 5 unsorted numbers





Step 3: Create 2nd Box

We will create a 2nd Box so that we have space to correctly place our numbers from our Input Box in the correct order. Some other algorithms may rearrange the numbers from within the Input Box, but in this demonstration, we are taking a 2nd Box approach.


Input Box 2nd Box



Step 4: Find the Lowest Number and Move it

This is the longest and largest step. In this step, you will identify the smallest number in the Input Box, then move it to the 2nd Box. This step will be repeated until the Input Box is completely empty.

Input Box 2nd Box


After repeating this process one by one, your boxes will look like this:




Step 5: Finalize

That’s it! You sorted an unsorted box! Now all we have to do is “Return” the 2nd Box, which is just a fancy way of saying output it. Once we output the 2nd Box, we can forget about the Input Box, and that is the end of the algorithm!


2nd Box - Output




How to code a Low-Level Algorithm using Python

As I stated in the introduction, this article assumes that you have no programming knowledge, so before we tackle the algorithm, we’re going to go over some basics. This tutorial is very simplified, so if you want more in-depth explanations, I recommend finding a Beginner's Python YouTube tutorial that covers these topics in depth.

First, let’s figure out WHERE to code. There are many ways to run Python code; some may use an Integrated Development Environment (IDE), which you may use if you would like, but in this demonstration, we will be using an online interpreter.


I will be using CodeHS as my online interpreter, but you're free to use anything. I will list some online interpreter sites below.

  • CodeHS

  • Replit

  • GDB Online Debugger

  • Online Python

  • W3Schools


Basics of Python:

Once you open the Python interpreter, your screen should look somewhat similar to the image below. There is a text editor portion, which is where we will write our code, and a console next to the text editor portion, where we will visualize our code.


Print Statements:

You may see the customary “print(‘Hello world’)” inside the text editor, which is a great way to segway into our next topic: Print Statements. Print statements are a way of telling the computer to print something into the console. For instance, if I type “print(‘Walker is so cool’)” and then press the “Run” button, the computer will print “Walker is so cool” in the console.


Try typing whatever you want in the print statement to test it out. We will be using the print statement to visualize the movement of our data in our algorithm.


Variables and Math:

In programming, there are many concepts from math that we also have, like Variables.


In the text editor, you can type a simple statement like “x = 3”. This is just like in your Algebra class, where a letter/word can hold the place of a number. You can also do mathematical operations in Python. For example, if you type “x = 6/2” (6 divided by 2), then “x” will be set equal to “3”. Some of the mathematical signs in Python are “*”(Multiplication), “/”(Division), “+”(Addition), “-”(Subtraction), and “%”(Modulus).


Now, try printing the variables themselves. If you type “x = (6/2)*4” and then type below that on the new line “print(x)”, it will print “12” into the console.


You can also set a variable equal to words. Try “ x = ‘Algorithms’ ”, then print it. It’s the same as just printing “ ‘Algorithms’ ” by itself.


Test the print, variables, and math concepts however you would like to get the hang of it.


IF Statements and Booleans:

IF statements are very easy to understand but can take a good minute to understand the full capacity of its capability.


To start the introduction to IF statements, we have to cover a thing called Booleans. A variable that holds a Boolean Value can be either True or False. It seems simple, but there is an entire category of algebra called “Boolean Algebra” which covers the full extent of Booleans (which we won’t cover). There are a large number of boolean operators to help compare boolean values, but in this demonstration, we will only be using the math Boolean Operators and the equivalence operators, which are:

  • “>”(greater than?

  • “<”(less than?)

  • “>=”(greater than or equal to?)

  • “<=”(less than or equal to?)

  • “==”(equals?).

These operators will take numbers and booleans and turn them into True or False values.

In your text editor, type “y = True”, then below that type “y = 2>1”. “y” in this case will be True, because 2 is larger than 1, and “x” is also set to True. This means that if we use the “==”(equals?) operator to compare “x” and “y” we can see if they equal the same value, which is True.


In your text editor, type “print(x==y)”, and it should print out “True”, since “x” and “y” have equal values.



IF statements work with booleans directly. IF statements execute a specific segment of code if a value is equal to true.


if 2>1:

print(“2 is greater than 1!”)


When you press “Run” the output in the console should be “2 is greater than 1”. This is because the statement “2>1” equals True, and since it’s True, the code indented afterward will be run.


Now, change the > greater than symbol to a < less than symbol, and you will notice that nothing will print, since “2<1” is a False statement.


There is a second component to IF statements that helps execute code segments if the statement is False, called an ELSE statement.


Make a third line in your text editor and delete the automatic indent. In this line type:


else:

print(“2 is not less than 1!”)


Once you run this program the output should be “2 is not less than 1!” since the statement “2<1” is false which means the ELSE statement segment will run.



The reason we would use an ELSE statement is so a certain segment of code will run ONLY if the IF statement is False.


Play around with Booleans, IF, and ELSE statements on your own to get the hang of it.


Functions:

Functions in programming and Functions in math are the exact same. In math you may come across a function like “f(x) = x+2”, and you could pass in a number as “x” to get a certain output. For instance we could say “f(2) = 2+2”, then “f(2) = 4”. This concept is the exact same in programming.


In your text editor, type what you see in the image below.


On line 1 we see “def myFunction(x)”. The word “def” basically tells the computer that you are creating a function. “myFunction” is simply the name of the function, similar to how “f” in “f(x)” is the name of the function.


After line 1 you see lines 2-5 are indented, which means lines 2-5 belong to the function. The IF and ELSE statements simply check if the value passed in through “x” is greater than 100 or not.


Then, after we skip line 6 to make it easier for us to read, we call the “myFunction” function twice. The first time we pass 80 into the function, and the second time we pass 120. If you look at the console after this program is run, you’ll see “X is not greater than 100!”, because 80 is not greater than 100, and “X is greater than 100!” because 120 is greater than 100.

This is the basic concept of functions. You make a code segment that executes something, and you can call it multiple times with different variations of input using a function.


Try playing around with functions by adding different variations of conditions and inputs!


FOR Loops and WHILE Loops:

A FOR Loop is a way of repeating a code segment a finite amount of times. If I tell a FOR Loop to repeat 5 times, then it will run all of the code inside of it 5 times. Below is an example.


The word “for” tells the computer that you are creating a FOR Loop. “i” is a temporary variable that is equal to the iteration of the loop that you are on minus 1. If you are on loop 3 of 5, then “i” will equal “2”. This is because in programming, most things are “0-indexed”, which means things will start counting at 0. Next, “in range(5)” tells the computer that you want it to repeat the following code 5 times. As you can see above, the code printed 5 numbers, numbers 0,1,2,3, and 4.


It is key to remember that FOR Loops are 0-indexed, and “i” is equal to the iteration of the loop you are on.


The next type of loop we will cover is the WHILE Loop. This loop is very simple. It will loop infinitely until a Boolean value is no longer true. See the image below.



In line 2 I inserted the WHILE Loop. It reads “while num < 10”, which just means “repeat while num is less than 10”. This means when num equals 10 the loop will stop. This loop is very simple but dangerous. If the Boolean condition in the while loop never has an opportunity to turn to False then your code WILL crash, due to an infinite loop. Because of this, WHILE Loops are often avoided, and FOR Loops are preferred.


Review

Below I am going to show an example of Prints, Variables, Math, IF/ELSE statements, Booleans, Functions, and FOR Loops used all in unison. Try your best to understand it fully, and please use previous examples as references if you are confused.



I know, I know, this is a lot, but don’t worry, I’ll break it down line by line.


In line 1 I created a function named “multiplyAndDivide” and passed in the variable “x”. This function's job is to multiply “x” by 2 if it’s less than 100 and divide it by 3 if it’s greater than 100. It will repeat that process 5 times. After the 5 loops, it will print the original number and the new number.


In line 2 I made a temporary variable called “hold”, which will hold the value of “x” so that we can print it after the process of multiplying and dividing to show the original number.

In line 3 I created a FOR Loop that repeats lines 4-7 5 times.


In lines 4-7 I created a IF/ELSE statement pear that compares “x” to 100. If “x” is less than 100 then it will run “x = x*2” which multiplies the value of “x” by 2. If it is not less than 100, then it runs “x = x/3” which will divide the value of “x” by 3.


In line 8 I printed the “hold” variable, which held the original value of ”x” before it was multiplied/divided.


In line 9 I printed the new value of “x” after it was modified.


Line 10 was skipped for spacing to be easier to read.


In line 11 I created a variable called “myNumber” which holds the number I want to pass into the function.


Line 12 was skipped for spacing to be easier to read.


In line 13 I passed “myNumber” into the “multiplyAndDivide” function for it to be executed.

That’s it! Well done!


Final Topic: Arrays

An array is a way of holding multiple separate values in one variable. Similar to a list of numbers, an Array holds multiple values, with each value getting its own index, as shown in the image below.


Visualization of Array, via Study Algorithms


Similar to how FOR Loops are 0-indexed, Arrays start at 0. This concept makes it easy to “traverse” an array using a FOR Loop. Most array-based algorithms use FOR Loops to “traverse” the array, which means accessing each individual value inside the array. One might use a FOR Loop to traverse an array by accessing a value of an array in each loop by using the built-in temporary variable of a FOR Loop. See the image below.



In line 1, I created an array. The brackets tell the computer that I am creating an array, and the commas separate the individual elements inside the array.


In line 3, I created a variable named “lengthOfArray”, which holds the length of the array. I did this by using the built-in Python function called “len()”. By passing in the array, “myArray”, to “len()”, it returns the length of the array and assigns it to “lengthOfArray”.


In line 5, I created a FOR Loop and passed in the variable “lengthOfArray”. This means that no matter how big the array is, the FOR Loop will always loop however large the array is.


In line 6, I created a print statement that prints the value of “myArray[i]” in every loop. The statement “myArray[]” tells the computer that I want to access a certain element from the “myArray” array. By passing in “i”, I access the element of the array whose index is equal to our current loop.


For example, on the first loop, “i” is equal to 0, so stating “myArray[i]” is the same as saying “myArray[0]”, which accesses the first element in the array. Then on the second loop “i” will be equal to 1 which will access the second element in the array. As I stated previously, the fact that FOR Loops and Arrays are both 0-indexed allows FOR Loops to easily traverse the array.


If you look to the right, at the console, you will notice that every element of the array has been printed. This concept of traversing and printing elements in the array will be used in our final algorithm.


Now that you know how Arrays work, I am going to introduce you to 2 VERY helpful built-in functions to Python. These functions being “.append()” and “.remove()”. See the image below.



In line 1, I created an array.

In line 4, I used the “append” function to add “5” to the end of the array.

In line 7, I used the “remove” function to remove “1” from the beginning of the array.


Please play around with arrays on your own before continuing, and make sure you have it down.


Coding your first Low-Level Algorithm

Now that you have learned the necessary skills, let’s use them!


This algorithm is a Sorting Algorithm. In fact, it is the same exact algorithm you read about above, in the “How Algorithms work - Brief Example” section, with the boxes. Only this time we will be using Arrays as our boxes. Let’s get started!


First, we want this algorithm to be able to take an input and give out an output. Since we want an input and an output, we will use Functions! This function will take an input of an array, “myArray”, and print out the sorted version of “myArray”.



Next, we want to go ahead and make our “2nd Box”, or in our case “2nd Array”. This will hold our sorted numbers, so will name the array “sortedArray”. This array will be empty since it hasn’t had any numbers from the unsorted array moved to it yet, so we’ll set it equal to “[]”.



Next, we are going to use a WHILE Loop. We will use this while loop to keep repeating the operation of “moving” the numbers from the unsorted array to the sorted array until the unsorted array is empty. This ensures that every number will be moved because the code won’t stop until the unsorted array is completely empty.


We will use “while len(myArray) > 0”, which basically means “repeat until the length of the unsorted array is 0”, which also means “repeat until empty”


Now we need to create the process of moving individual values from the unsorted array to the sorted array. This process will be repeated by the WHILE Loop for each individual value.


In order to sort the array, we need to find the smallest number in the unsorted array so we can move it to the sorted array. The first step to this is creating a variable that will hold the value of the smallest number. We will name it “least”, and it will (at first) hold the value of the first index in the unsorted array. This is so we have a base value to compare all the other numbers in the array to. We will type “least = myArray[0]”.


Next, we need to loop through each element in the unsorted array so we can compare it to “least” and find the smallest number. We will do this by creating a FOR Loop and making it loop the current length of the unsorted array. We will type “for i in range(len(myArray)):”. Remember, “len(myArray)” is the length of “myArray”, and we’re setting the number of loops in the FOR Loop equal to that.



Now that the code will loop through the unsorted array, we need to find the lowest value. We will do this by using an IF statement that compares the current array index of the loop to “least”. If the current array index of the loop is less than “least”, then we will assign the value of the current index to “least”, since it is the smallest number so far.




Remember, “i” is equal to the current loop number, so when we say “myArray[i]”, we’re saying “access the value of the array with the index of our current loop”. So on loop 3 it will access index 2 (0-indexed) and compare it to our current “least” number, and if index 2 is less, then it will assign the value of index 2 to “least”.


After we find our smallest number, and it is stored in “least”, we just need to move it from the unsorted array to the sorted array. We will accomplish this by using our handy-dandy “.append()” and “.remove()” functions. We will remove the “least” value from our unsorted array, and append the value to our sorted array. This is essentially the same as moving our numbers from one box to the next.



This process of locating the smallest number and moving it will be repeated until the unsorted array is empty. This means that all we need to do is print the sorted array after the while loop, and we’ve created the sorting algorithm. YAYYY!!!



NOW!! LETS TEST!!


Create a randomly unsorted array. (Yes, I went overboard)


Then, pass the unsorted array into the function and watch the magic! Notice the console on the right, it printed the array from least to greatest. THAT’S IT!!



You Did It!

You learned what an algorithm is, how an algorithm works, the basics of Python, AND you made your own miniature algorithm!

 

Walker Jackson is a 16-year-old from Texas, who has a passion for Computer Science, loves playing tennis with friends when it’s not 100 degrees outside, and cherishes the small things.

1 Comment

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Guest
Oct 13, 2023
Rated 5 out of 5 stars.

Intriguing!

Like
bottom of page