Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

Insertion Sort Implemented

Here is a Python implementation of Insertion Sort:

 def​ ​insertion_sort​(array):
 for​ index ​in​ range(1, len(array)):
 
  position = index
  temp_value = array[index]
 
 while​ position > 0 ​and​ array[position - 1] > temp_value:
  array[position] = array[position - 1]
  position = position - 1
 
  array[position] = temp_value

Let’s walk through this step by step. We’ll first present the line of code, followed by its explanation.

 for​ index ​in​ range(1, len(array)):

First, we start a loop beginning at index 1 that runs through the entire array. The current index is kept in the variable index.

 position = index
 temp_value = array[index]

Next, we mark a position at whatever index currently is. We also assign ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page