If you want to learn how to code, you need to learn algorithms. Learning algorithms improves your problem solving skills by revealing design patterns in programming. In this tutorial, you will learn how to code a swap algorithm in JavaScript and Python.
đŻ Give yourself an A. Grab your copy of A is for Algorithms
Retrieval Practice
Retrieval practice is the surest way to solidify any new learning. Attempt to answer the following questions before proceeding:
-
What is programming?
-
What is pseudocode?
-
What is Big O?
What is Programming?
Programming is problem solving. There are four steps we need to take to solve any programming problem:
-
Understand the problem
-
Make a plan
-
Execute the plan
-
Evaluate the plan
What is Pseudocode?
Pseudocode is an approach to designing and solving algorithms using plain language rather than the syntax of a specific programming language. Writing pseudocode allows us to focus on the solution to the problem rather than the details of its implementation. If youâre just joining us, you may want to start with Learn How to Write Pseudocode by Solving the Classic Fizz Buzz Algorithm.
What is Big O?
Big O is a notation for measuring the complexity of an algorithm. Big O notation mathematically describes the complexity of an algorithm in terms of time and space. We donât measure the speed of an algorithm in seconds (or minutes!). We measure the rate of growth of an algorithm in the number of operations it takes to complete. If youâre new to Big O, check out The Superlative Guide to Big O.
Letâs Get Meta
Programming and problem solving are both metacognitive activities. To excel, we want to improve our thinking about thinking. Ask yourself the following questions and keep them back of mind as you proceed:
-
What is computational thinking?
-
What problem(s) does a swap algorithm solve?
-
What is the Big O of swap?
How to Code a Swap Algorithm in JavaScript
How do you think like a programmer?
If programming is problem solving, we need one or more heuristics specific to this domain.
Weâre in luck!
Thereâs a set of methods used for defining and solving a problem in terms that a computer could also perform. Itâs called, youâll never guess⌠computational thinking.
Computational thinking is a set of methods used for defining and solving a problem in terms that a computer could also perform.
There are four stages to computational thinking:
-
Decomposition
-
Pattern recognition
-
Abstraction
-
Algorithm design
Weâll look at each of these in depth as we proceed with our problem solving. The first step is to understand the problem. Our workflow will follow with outline:
-
Understand the problem
-
Make a plan
-
Decompose the problem
-
Recognize patterns
-
Form abstractions
-
Design the algorithm
-
-
Execute the plan
-
Evaluate the plan
Understand the Problem
To understand our problem, we first need to define it. Letâs reframe the problem as acceptance criteria:
GIVEN two variables
WHEN I perform a swap
THEN the values are exchanged
Thatâs our general outline. We know our input conditions (two variables) and our output requirements (exchanged values between the variables), and our goal is to swap them.
Letâs make a plan!
Make a Plan
As outlined above, this is where we implement our computational thinking heuristics, the first being decomposition.
Decomposition
If composing a function is the process of assembling the various components, such as variables, control flow, and conditions, then decomposition is the opposite: itâs breaking a problem down into smaller parts.
This is both the easiest and the hardest step in the process because sometimes the component parts of a problem are obvious, but other times the component parts are emergent, or intertwined, and itâs difficult to cleanly separate them.
Letâs break this problem down and start by declaring two variables, x
, and y
. Each of these variables stores a value. We need values to swap, so letâs just sayâŚ
x = 123
y = 456
Our goal is to swap the value stored in x
, 123, with the value stored in y
, 456. When we are decomposing a problem, we want to break the problem down into the the smallest problem we can solve. So letâs just focus on x
. How do we move the value stored in y
to the variable x
?
Easy.
x = y
How would we pseudocde this?
SET x TO y
How do we move the value stored in x
to y
? Your initial thought might be to do something like this
x = y
y = x
Our pseudocode would look like thisâŚ
SET x TO y
SET y TO x
If we ârunâ this algorithm, whatâs the result?
x = 456
y = 456
Whatâs happening?
Following our control flow, we are overwriting the value of x
with the value stored in y
, which is 456. When we then assign the value of x
to y
, we are simply reassigning the value of 456.
Pattern Recognition
When we break a problem down into smaller pieces, we will often recognize patterns. Another way of saying this is that we generalize. We make a broad statement by inferring from specific cases.
Letâs take a look at our pseudocode againâŚ
SET x TO y
SET y TO x
Whatâs the pattern?
Variable assignment.
If only we could set the value of x
aside, temporarily, while we performed our swapâŚ
Abstraction
Once we recognize patterns, we can remove the details, or form abstractions, in order to focus on the relationships between concepts.
Weâre already working with abstractions using variables such as x
and y
, but we were thinking in terms of the specific value stored in those variables. In the abstraction step of computational thinking, the value isnât important. Why doesnât the value matter? In this algorithm, weâre more interested in where the value is stored then what the value is.
Knowing that, we need to declare another variable that allows us to temporarily store one of the values we want to swap. Letâs call it temp
:
SET temp TO x
SET x TO y
SET y TO temp
Execute the Plan
Finally, we simply need to implement the design of our algorithm.
How to Code the Swap Algorithm in JavaScript
Here, we translate our pseudode to JavaScript:
let x = 123;
let y = 456;
const swap = (x, y) => {
let temp = x;
x = y;
y = temp;
return [x, y];
}
If we run this algorithm and log the value returned, the result is:
[456, 123]
How to Code the Swap Algorithm in Python
x = 123
y = 456
def swap(x, y):
temp = x
x = y
y = temp
return [x, y]
Again, if we run this algorithm and print the value returned, the result is:
[456, 123]
Evaluate the Plan
If temp
was a value you were planning to update again, you may want to declare it without value assignment or assign a value of 0 to initialize it as a number.
let x = 123;
let y = 456;
let temp; //or let temp = 0
temp = x;
x = y;
y = temp;
With Python, just omit the let
statements and the semicolons.
With both JavaScript and Python you can omit the temp
variable (and semicolons) and get mathemagical:
x = 123
y = 456
x = x + y
y = x - y
x = x - y
You can accomplish the same feat as above with multiplication and division:
x = 123
y = 456
x = x * y
y = x / y
x = x / y
The downside to both of the approaches above is that they can only be used for numeric values.
In Python, you can do a one-liner using parallel assignment:
x, y = y, x
Reflection
Remember those questions we asked at the top? Letâs make it stick and answer them now:
-
What is computational thinking?
-
What problem(s) does swap solve?
-
What is the Big O time complexity of swap?
What is Computational Thinking?
Computational thinking is a set of methods used for defining and solving a problem in terms that a computer could also perform.
There are four stages to computational thinking:
-
Decomposition
-
Pattern recognition
-
Abstraction
-
Algorithm design
What Problem(s) Does a Swap Algorithm Solve?
Beyond swapping the values stored in two variables, swap algorithms are used in sorting algorithms.
What is the Big O Time Complexity of Swap?
O(1), or constant.
Regardless of the size of the input, n
, the swap algorithm only performs one operation.
If you want to learn more about Big O, check out The Little Book of Big O.
A is for Algorithms
đŻ Give yourself an A. Grab your copy of A is for Algorithms