Jun17

Insertion Sort, Algorithm Source Code for C/C++

Algorithm Source Code
WP Greet Box icon
Hello there! If you are new here, you might want to subscribe to the RSS feed for updates on this topic.

Insertion sort is one of the most common sorting algorithms you’ll ever bump into. It is very simple and it takes time roughly equal to c*n2 to sort n items, where c is an undependable constant.

Input: a sequence of n unsorted numbers

Output: a sequence of permuted n numbers from the input such that those numbers are sorted in most of the time decreasing order.

grey Insertion Sort, Algorithm Source Code for C/C++

Image source: “Introduction to Algorithms”, The MIT Press

The image above explains the process used on an array of six numbers, as you can see at the end the result is a sorted array.

How it works

Indexes of numbers in this array are present above the rectangles, their connected values, on the other hand, appear in the rectangles. Have in mind that in C++ indexing starts at zero, and ends at length – 1.
In each iteration, the black rectangle represents the key taken from the current indexed number in for loop, which is being compared with all values in gray rectangles from it’s left. Gray arrows represent moving gray values one position to the right, and black arrow represent moving the key when appropriate.

Code realization

 

This function takes two parameters: the “a” array and the “length” integer that represent the number of it’s elements. It goes through the array as shown on the images and repositions it’s values so that you get a sorted array in decreasing order as an output which can be tested using printf function.

There is also a variant for getting the output in non-decreasing order:

 

This algorithm is very popular in terms of sorting short arrays, but for more complex situations you should better check out my Algorithms category and find what you need. Also, make sure to understand the code completely buy following through the function with your own example and figuring it out. Good luck!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Read previous post:
Essential Firefox Add-Ons for Web Designers and Developers
Close