Lecture 22:  Sorting2 -- Insertion

 

Objectives of this lecture

q       Lean the Insertion Sorting Method.

 

 

Insertion Sort:

q       This is another quadratic sorting method.

q       It has advantage over selection sort when the list is already sorted – it doest it in linear order (n times).

q       On a random data however, they are about the same.

q       In this method,  the list is conceptually divided into a destination sub-list a0, … ai-1 and a source sub-list, ai … an-1.   

q       In each iteration, the ith element of the source sub-list is picked and inserted at its proper position in the destination sub-list.

 

void InsertionSort(int list[])

 {   int i, j , temp;

      for(i = 1; i < MAX_SIZE ; i++)

      {     temp = list[i];

             j = i;

             while((j-1 >= 0) && list[j-1] > temp)

             {   list[j] = list[j-1];

                   j--;

             }

             list[j] = temp;

      }

 }

 

q       The following table shows a trace of insertion sort:

 

Index

Original

Round1

Round3

Round 3

0

7

2

1

1

1

2

7

2

2

2

1

1

7

4

3

4

4

4

7