InsertionSort Algorithm

One by one, each as yet unsorted array element is inserted into its proper place with respect to the already sorted elements.

On each pass, this causes the number of already sorted elements to increase by one.

 

 

 

 

Works like someone who “inserts” one more card at a time into a hand of cards that are already sorted.

 

 

 

 



To insert 12, we need to make room for it by moving first 36 and then 24.

 

 

 

 

Snapshot of InsertionSort

// CODE
template 
void InsertItem  ( ItemType  values [ ] ,   int  start ,  int end )		
//  Post: Elements between values[start] and  values 
//   [end] have been sorted into ascending order by key.
{
	bool  finished = false ;
	int   current  =  end ;
	bool  moreToSearch = (current != start);

	while (moreToSearch  &&  !finished )
	{	
	  if  (values[current] < values[current - 1])
	    {
        Swap(values[current], values[current - 1);
		 current--;
		 moreToSearch = ( current != start );
	    }
     else
		 finished = true ;
	}      
}


template 
void  InsertionSort  ( ItemType  values [ ] ,   
  int  numValues )	
	
//  Post: Sorts array values[0 . . numValues-1 ] into 
//   ascending order by key
{
	for (int count = 0 ; count < numValues; count++)

    InsertItem ( values , 0 , count ) ;
} 




Running Time

This algorithm is O(N^2).  

 

 

 

© Lynne Grewe