DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Algorithm of the Week: Insertion Sort

Algorithm of the Week: Insertion Sort

Stoimen Popov user avatar by
Stoimen Popov
·
Feb. 14, 12 · Interview
Like (0)
Save
Tweet
Share
20.91K Views

Join the DZone community and get the full member experience.

Join For Free

Sorted data can dramatically change the speed of our program.  Therefore, sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list.

There are two main approaches in sorting – by comparing the elements and without comparing them. A typical algorithm from the first group is insertion sort. This algorithm is very simple and very intuitive to implement, but unfortunately it is not so effective compared to other sorting algorithms such as quicksort and merge sort. Indeed, insertion sort is useful for small sets of data with about no more than 20 items.

Insertion sort is a very intuitive method of sorting items and we often use it when we play card games. In this case the player often gets an unordered set of playing cards and intuitively starts to sort it. First by taking a card, making some comparisons and then putting the card in the right position.

So let’s say we have an array of data. In the first step the array is unordered, but we can say that it consists of two sub-sets: sorted and unordered, where on the first step the only item in the sorted sub-set is its first item. If the length of the array is n the algorithm is considered completed in n-1 steps. On each step our sorted subset is growing with one item. The thing is, we take the first item from the unordered sub-set and with some comparisons we put it into its place in the sorted sub-set, like on the diagram bellow.

Main principle of insertion sort.

Main principle of insertion sort

 


The insertion itself is the tricky part. We can insert the item once we find an item with a smaller value or if we have reached the front of the array like on the diagram bellow.

Example of insertion sort

Insertion sort example

 

Implementation

Here’s a quick implementation of insertion sort in PHP. The good thing is that it is easy to implement, but there's bad news too – insertion sort is slow and ineffective for large data sets.

$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);
 
function insertion_sort(&$arr)
{
	$len = count($arr);
 
	for ($i = 1; $i < $len; $i++) {
		$tmp = $arr[$i];
		$j = $i;
 
		while (($j >= 0) && ($arr[$j-1] > $tmp)) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
}


We can improve this code a little by using a sentinel, just like the sequential search, in order to remove one of the comparisons.

$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);
 
function insertion_sort_sentinel(&$arr)
{
	$len = count($arr);
	array_unshift(&$arr, -1);
 
	for ($i = 1; $i < $len+1; $i++) {
		$tmp = $arr[$i];
		$j = $i;
 
		while ($arr[$j-1] > $tmp) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
	array_shift(&$arr); // remove the sentinel
}


Since we used searching in the right position in an ordered array, we can use binary search in order to improve the above algorithm even more. Unfortunately this doesn’t do much to improve the general efficiency of this algorithm.

Complexity

As I said this algorithm is not very effective. Its complexity is O(n2) which is far worse than the O(n*log(n)) of quicksort, as you can see on the diagram bellow.

n*n vs. n*log(n)

n*n vs. n*log(n)

 

Application

This algorithm is useful for small sets of data and even though it doesn’t look like the most effective sorting algorithm, insertion sort can be useful for a couple of reasons:

  1. It is easy to implement
  2. It does not require additional memory
  3. It can be fast if the data is almost nearly sorted


Which is great!


Source: http://www.stoimen.com/blog/2012/02/13/computer-algorithms-insertion-sort/

Insertion sort Sort (Unix) Algorithm

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using GPT-3 in Our Applications
  • 3 Main Pillars in ReactJS
  • Build an Automated Testing Pipeline With GitLab CI/CD and Selenium Grid
  • HTTP vs Messaging for Microservices Communications

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: