nextupprevious
Next:9.3 Selection SortUp:9. Sorting MethodsPrevious:9.1 Bubble Sort

9.2 Insertion Sort

Here in the ith iteration, the record a[i] is inserted into its proper position in the first i positions.
$\displaystyle \underbrace{a[1] \space \ldots \space a[i-1]}_{\begin{array}{l}\mbox{sorted (may not be as}\\\mbox{in the final order)}\end{array}}^{}\,$$\displaystyle \underbrace{a[i] \space \ldots \space a[n]}_{\begin{array}{l}\sp......{Insert $a[i]$ into an} \\\space \ \mbox{appropriate place}\end{array}}^{}\,$
Let us assume, for the sake of convenience, a fictitious record a[0] with key value = $ \infty$.



    {

            for(i = 2;i < = n;i + +)

            {

                j = i ;

                while (key of a[j] < key of a[j - 1])

                {

                    swap records a[j] and a[j - 1];

                    j = j - 1

                }

            }

    }




eEL,CSA_Dept,IISc,Bangalore