Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,875 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,921 people online right now. Registration is fast and FREE... Join Now!





Insertion Sort Example

Simply demonstrates how Insertion Sort works.

Submitted By: born2c0de
Actions:
Rating:
Views: 31,515

Language: C++

Last Modified: October 29, 2005

Snippet


  1. /*
  2.         Written by Sanchit Karve A.K.A born2c0de
  3.         born2c0de AT hotmail DOT com
  4. */
  5.  
  6.  
  7.  
  8. #include <iostream>
  9.  
  10.  
  11. #define ELEMENTS 6
  12.  
  13. void insertion_sort(int x[],int length)
  14. {
  15.   int key,i;
  16.   for(int j=1;j<length;j++)
  17.   {
  18.      key=x[j];
  19.      i=j-1;
  20.      while(x[i]>key && i>=0)
  21.      {
  22.                x[i+1]=x[i];
  23.          i--;
  24.      }
  25.      x[i+1]=key;
  26.   }
  27. }
  28.  
  29. int main()
  30. {
  31.   int A[ELEMENTS]={5,2,4,6,1,3};
  32.   int x;
  33.  
  34.   cout<<"NON SORTED LIST:"<<endl;
  35.   for(x=0;x<ELEMENTS;x++)
  36.   {
  37.        cout<<A[x]<<endl;
  38.   }
  39.   insertion_sort(A,ELEMENTS);
  40.   cout<<endl<<"SORTED LIST"<<endl;
  41.   for(x=0;x<ELEMENTS;x++)
  42.   {
  43.        cout<<A[x]<<endl;
  44.   }
  45.   return 0;
  46. }
  47.  

Copy & Paste


Comments


jeronimo0d0a 2008-03-03 08:52:50

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


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month