CS Comics

How to Implement Insertion Sort

by cscomics_etvvcs on September 7, 2018 at 10:34 pm
Posted In: Uncategorized

Insertion Sort goes from the second through the last number in a list, performing these steps with each number:

  • Compare with the previous number
  • If it’s less than the previous number, swap it with that number
    • If swapped, then repeat this with the number before that…
    • …and so on, until we find a number that’s not bigger than it, or we reach the beginning of the list.

Pretty simple, right?  Okay, but how do we make a computer actually do this?  Just follow those steps!

A program in the language called C++ doing this might look like:

int main() {
  int the_list[] = {3, 7, 8, 5, 2, 1, 9, 5, 4};
  int size_of_the_list = 9;

  for (int current_index = 1;
       current_index < size_of_the_list;
       ++current_index) {
    // Put the_list[current_index] into its rightful place
    // among all preceding numbers.
  }

  return 0;
}

If you’re not familiar with C++, the “int main()” just indicates where the program starts and you can basically ignore it, just like when you read, “Once upon a time,” in a story.

Similarly, “return 0” just means the program shall end successfully when that line of code is executed, so you can basically ignore it, just like “The End” in a story.

You can probably tell that the first “real” line of code is just listing the 9 numbers we want to sort, and the second line is just specifying how many numbers are in that list to be sorted (9).

Then, there is this thing called a “for loop,” which:

  • executes the first command in it (int current_index = 1) once,
  • checks the “loop condition” (whether current_index is less than size_of_the_list),
  • and if that condition is true, then runs whatever code is between the braces {},
  • and then runs the “loop increment” (++current_index, which means the same as current_index = current_index + 1, or in plain English, “increase current_index by one”).

Then, the for loop again checks the loop condition and if it’s true, it again runs the code inside the braces, and then does the loop increment again, and then checks the loop condition again, and if it’s true, runs the code inside the braces, does the loop increment again, etc. This just keeps repeating until the loop condition ends up being false.

But this isn’t a complete program yet: notice that inside the braces of the loop, all we have is a couple lines in plain English starting with two slashes.  This is called a “comment” and is not “really” part of the code–it’s just an aid to someone reading the code to describe what needs to happen in that part of the code.

Okay, so how do we write the code to implement what the comment says?  How do we take a number in a list and keep comparing and swapping it with all numbers that come before it that are bigger than it, until we reach a number that isn’t bigger than it (or, we reach the beginning of the list)?  Well, that sounds like something we keep repeating… which means, we need another loop!

What should this new loop do?  Well,

  • if we set j to current_index,
  • the loop should take the number the_list[j] and compare it with the_list[j-1],
  • and if the latter number is bigger, then swap these two numbers.
  • If we did end up swapping these two numbers, then the number of interest is now at the_list[j-1].
  • So in that case, let’s set j equal to j-1, so now the number of interest is at the_list[j].
  • Then we should continue up the list, checking if the_list[j] is smaller than the number before it, the_list[j-1], and swapping if so, and so on, …
  • …until either j is 0, meaning we’re at the beginning of the list, or the_list[j-1] is not bigger than the_list[j].

So now we’ve figured out:

  • where we should start this for loop (int j = current_index),
  • what we should check before we run the loop each time (j > 0 and the_list[j] < the_list[j-1]),
  • and what we should do inside the loop (swap the_list[j] and the_list[j-1]).
  • We also know how to update j after each time the loop runs: j = j – 1, or in C++ shorthand, –j.

So let’s plug that into our code where that comment was:

int main() {
  int the_list[] = {3, 7, 8, 5, 2, 1, 9, 5, 4};
  int size_of_the_list = 9;

  for (int current_index = 1;
       current_index < size_of_the_list;
       ++current_index) {
    // Put the_list[current_index] into its rightful place
    // among all preceding numbers.
    for (int j = current_index;
         j > 0 && the_list[j] < the_list[j-1];
         --j) {
      // Swap the_list[j] and the_list[j-1].
    }
  }

  return 0;
}


Okay, now all we have left is to figure out how to swap two numbers!  That’s simple: just create a third number as a placeholder, like this:

int main() {
  int the_list[] = {3, 7, 8, 5, 2, 1, 9, 5, 4};
  int size_of_the_list = 9;

  for (int current_index = 1;
       current_index < size_of_the_list;
       ++current_index) {
    // Put the_list[current_index] into its rightful place
    // among all preceding numbers.
    for (int j = current_index;
         j > 0 && the_list[j] < the_list[j-1];
         --j) {
     // Swap the_list[j] and the_list[j-1].
     int placeholder = the_list[j];
     the_list[j] = the_list[j-1];
     the_list[j-1] = placeholder;
    }
  }

  return 0;
}


Let’s also add some lines of code to print the sorted list to the computer screen, so we can see that this program actually does what we want!

#include <iostream>

int main() {
  int the_list[] = {3, 7, 8, 5, 2, 1, 9, 5, 4};
  int size_of_the_list = 9;

  for (int current_index = 1;
       current_index < size_of_the_list;
       ++current_index) {
    // Put the_list[current_index] into its rightful place
    // among all preceding numbers.
    for (int j = current_index;
         j > 0 && the_list[j] < the_list[j-1];
         --j) {
      // Swap the_list[j] and the_list[j-1].
      int placeholder = the_list[j];
      the_list[j] = the_list[j-1];
      the_list[j-1] = placeholder;
    }
  }

  // Print the sorted list to the computer screen.
  for (int i = 0; i < size_of_the_list; ++i) {
    std::cout << the_list[i] << “ “;
  }
  std::cout << std::endl;

  return 0;
}

And voila, we have a complete computer program that implements the Insertion Sort algorithm!  Read more on Wikipedia about how this implementation can be improved.

 Comment 

Another Simple Program: An Assignment and a Print Statement

by cscomics_etvvcs on September 7, 2018 at 10:13 pm
Posted In: Uncategorized

 Comment 

A Simple Program: Just a Print Statement

by cscomics_etvvcs on September 7, 2018 at 9:14 pm
Posted In: Uncategorized

 Comment 

A Print Statement Is Another Kind of Instruction

by cscomics_etvvcs on September 7, 2018 at 9:11 pm
Posted In: Uncategorized

 Comment 

An Assignment Is One Kind of Instruction

by cscomics_etvvcs on September 7, 2018 at 9:08 pm
Posted In: Uncategorized

An assignment, like we just saw, is one kind of instruction.

 Comment 
  • Page 6 of 18
  • « First
  • «
  • 4
  • 5
  • 6
  • 7
  • 8
  • »
  • Last »

My TED-Ed Video Lesson: > 3.5 Million Views

  • #11 trending video on YouTube shortly after release
  • Featured by BBC News Brasil (in Portuguese and Spanish)
  • Featured by Quartz, Boing Boing, Digital Trends, LifeHacker, IMDB, and Reddit
  • Teaches computer science topic: sorting algorithms

University of Texas Homepage Highlights My Teaching

  • I was the "homepage hero" of the Computer Science Department
  • UT-Austin Faculty Innovation Center features my teaching

University of Texas Features My Comics on Leading Women in Mathematics

  • One Step Deeper #2: Katherine Johnson
  • One Step Deeper #1: Ada Lovelace

Chief Meteorologist Shares My Weather Comics

  • Ridges & Troughs with Bad Puns [More Info]
  • Compressional Warming [More Info]
  • Why Is It Hot Before a Cold Front? [More Info]
  • What Meteorologists Do [More Info]
  • How Clouds Make Snow [More Info]

Learn to Physically Simulate a Fluid

  • From first principles and C++, using only free, widely available software, create and visualize a physics-based simulation of a fluid

Learn to Code by Character Animation

  • I modified a Blender plug-in to enable writing Python code that directs 3D animated characters to dance, throw a basketball, and climb.

ACM Inroads Back Page Features My Comic

  • Learn how computers store letters in their memory
  • Learn about abstraction

Math Comics

  • What Is A Cauchy Sequence?

Weather Comic: How High and Low Pressure Centers Form

  • Page 1
  • Page 2
  • Page 3
  • Page 4
  • Page 5
  • Page 6
  • Page 7
  • Page 8
  • Page 9
  • Many more pages in progress...!

Comics on Computer Programming Concepts

  • Programs are recipes telling computers how to "cook" data.
  • Programs have ingredients & instructions.
  • Ingredients in a program are like boxes.
  • Each box has a unique name.
  • Each box has a data type.
  • Boolean data type
  • Character data type
  • Integer data type
  • Float data type
  • Box = Variable
  • Value of a Variable
  • Primitive data types
  • Data structures
  • Arrays
  • Array of integers
  • Array of characters
  • Strings
  • Declaring a variable
  • Assigning a value to a variable
  • Assigning a new value to a variable
  • Ingredients of a program are variables.  What are instructions?
  • An assignment is one kind of instruction.
  • A print statement is another kind of instruction.
  • A simple program: Just a print statement
  • Another simple program: An assignment and a print statement

Comics on How Computers Store Data

  • Computers Can Cook Data, but We Have to Write the Recipes
  • Computers Remember and Do Things Kind of Like Us
  • Computers Use Secret Codes Called Data Types to Store Data Using 0s and 1s
  • Boolean -- Yes and No
  • Boolean -- Housing the Truth
  • Houses of Character
  • Computers Use Blocks of Memory to Represent Larger Pieces of Data
  • Liar Paradox or a Joke for Computers

Comics on How Computers Run Programs

  • The Life of a Computer Program, Part 1: Fetching the Recipe
  • The Life of a Computer Program, Part 2: Virtual Memory
  • The Life of a Computer Program, Part 3: Program Segments
  • The Life of a Computer Program, Part 4: How Computers Store Programs
  • The Life of a Computer Program, Part 5: How a Computer Adds Two Numbers
  • The Life of a Computer Program, Part 6: How a Computer Runs a Program
  • How an Array of Integers Gets Stored in Memory
  • Computers Don't Know Anything, but They Compute Quickly

Comics on How to Computers Search Data

  • Linear Search, Part 1: A Simple Algorithm
  • Linear Search, Part 2: Program Walk-through and For Loop
  • Linear Search, Part 3: How the Program Works
  • Linear Search, Part 4: How to Understand a Program
  • Binary Search, Part 1: The Algorithm
  • Binary Search, Part 2: A Play & Poem
  • Binary Search, Part 3: How to Implement It
  • Binary Search, Part 4: How It Runs

Comics on How Computers Sort Numbers

  • Algorithms, Page 1
  • Algorithms, Page 2
  • Insertion Sort, Page 1
  • Insertion Sort, Page 2
  • Insertion Sort, Page 3
  • How to implement Insertion Sort
  • Quicksort, Page 1
  • Quicksort, Page 2
  • Quicksort, Page 3
  • Quicksort, Page 4
  • Quicksort, Page 5
  • How to implement Quicksort

Data Science / Machine Learning Comics

  • Linear Regression & Gradient Descent, Page 1
  • Linear Regression & Gradient Descent, Page 2
  • Linear Regression & Gradient Descent, Page 3
  • Linear Regression & Gradient Descent, Page 4
  • Linear Regression & Gradient Descent, Page 5
  • Linear Regression & Gradient Descent, Page 6
  • Linear Regression & Gradient Descent, Page 7
  • Linear Regression & Gradient Descent, Page 8
  • Linear Regression & Gradient Descent, Page 9

Physics Comics

  • A Rock Goes 0 to 60 in 3 Seconds

Older Comics

  • A Comic for All of Us, Especially Girls and Women, to Learn and Enjoy Computer Science

©2017-2023 CS Comics | Powered by WordPress with ComicPress | Subscribe: RSS | Back to Top ↑