# Insertion Sort Example

Page 1 of 1

## 5 Replies - 2336 Views - Last Post: 28 June 2012 - 05:21 AM

### #1 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 187
• Posts: 4,673
• Joined: 26-November 04

# Insertion Sort Example

Posted 29 October 2005 - 03:39 AM

Description: Simply demonstrates how Insertion Sort works.
```/*

Written by Sanchit Karve A.K.A born2c0de
born2c0de AT hotmail DOT com
*/

#include <iostream>

#define ELEMENTS 6

void insertion_sort(int x[],int length)
{
int key,i;
for(int j=1;j<length;j++)
{
key=x[j];
i=j-1;
while(x[i]>key && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}

int main()
{
int A[ELEMENTS]={5,2,4,6,1,3};
int x;

cout<<"NON SORTED LIST:"<<endl;
for(x=0;x<ELEMENTS;x++)
{
cout<<A[x]<<endl;
}
insertion_sort(A,ELEMENTS);
cout<<endl<<"SORTED LIST"<<endl;
for(x=0;x<ELEMENTS;x++)
{
cout<<A[x]<<endl;
}
return 0;
}

```

Is This A Good Question/Topic? 0

## Replies To: Insertion Sort Example

### #2 jeronimo0d0a

Reputation: 1
• Posts: 146
• Joined: 03-March 08

## Re: Insertion Sort Example

Posted 03 March 2008 - 06:52 AM

A great simple, to the point snippet to learn from.

### #3 cmaster

Reputation: 2
• Posts: 53
• Joined: 18-November 08

## Re: Insertion Sort Example

Posted 03 May 2009 - 05:19 AM

See an explanation here http://simpleprogram...ertion-sort.php

### #4 navidkhan

Reputation: 0
• Posts: 0
• Joined: 24-August 10

## Re: Insertion Sort Example

Posted 24 August 2010 - 12:00 AM

Thanx

• D.I.C Lover

Reputation: 331
• Posts: 1,168
• Joined: 01-April 11

## Re: Insertion Sort Example

Posted 19 July 2011 - 11:11 AM

Good example. Insertion sort is VERY fast when the array is relatively small, or the array is close to being sorted, already. I use it to handle small sub arrays for Quicksort, and it is a big help.

### #6 praba123

Reputation: 0
• Posts: 0
• Joined: 28-June 12

## Re: Insertion Sort Example

Posted 28 June 2012 - 05:21 AM

Hi The code was very useful. However, the line while(x[i]>key && i>=0) gave me a lot of grief. I could avoid Assertion Failure -- subscript out of range error only by rearranging the condition as in while(i>=0 && x[i]>key) Otherwise, when i became -1, an error was generated. Hope this input helps somebody. Regards