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

#1 born2c0de   User is offline

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

Reputation: 187
  • View blog
  • 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   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

#3 cmaster   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

#4 navidkhan   User is offline

  • New D.I.C Head

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

Re: Insertion Sort Example

Posted 24 August 2010 - 12:00 AM

Thanx
Was This Post Helpful? 0
  • +
  • -

#5 Adak   User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

#6 praba123   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1