Insertion Sort
What
is sorting?
Suppose
you are playing a multiplayer game with your friends on a computer. Each player
is rewarded some points at the end of the game. As the game finishes, we need
to display the score of each player on the screen with the lowest score at the
bottom and the score gradually increases as we move toward the top. So, the
process of arranging the numbers in this order is called sorting.
How
can we arrange numbers in such order? Well, there are different algorithms to
do so but, here we discuss a basic algorithm called insertion sort. The concept
of insertion sort can be easily understood with the following example. This
example is taken from the CLRS book Introduction to Algorithms. Suppose we have to sort a hand of playing cards. Initially, the
left hand is empty and the cards are facing down on the table. We then, remove
a card from the table at a time and place it in the right position on the hand.
To do so, we compare the card (say X) which we picked with the rightmost card
on the left hand. If it is greater than the rightmost card, then the new card
(card X) is now the rightmost card. Otherwise, the new card is compared with
the next card left to the rightmost card. In this way, the card is compared
from right to left until a card smaller than the card X is found on the hand.
We can see that the cards on the left hand are sorted at all times.
Input to the algorithm:
The sequence of numbers, a1,
a2, a3, …, an.
Output
from the algorithm: The
reordering of numbers, a1’, a2’, a3’, …, an’
such that a1’ < a2’ < a3’ < … < an’.
Here
is the pseudocode for the insertion sort.
Insertion-Sort (A) // A is the array
of numbers to be sorted
1. for j = 2 to A.length
2. key = A[j]
3.
i = j – 1 //A[j] is inserted into the sorted sequence
A[1 … j-1]
4.
while i > 0 and A[i] > key
5.
A[i+1] = A[i]
6.
i = i -1
7.
A[i+1] = key
The
worst case running time of insertion sort is θ(n2) where n is the
length of the array. To see this, let us consider a barometer instruction (the
instruction which is executed most). Here, we consider instruction in line 5 as
a barometer instruction. Considering the outer for loop, line 5 is executed
(n-1) times. With the while loop, line 5 is executed (j – 1) times which is
equal to (n-1) in the worst case i.e. when the given array is sorted in reverse
order then, the last element to be inserted to the array A[1…j-1] will take
(n-1) times. This is just an intuition behind the fact that running time of
insertion sort is bounded by θ(n2). For detail proof, see Introduction to Algorithms book by
CLRS.
Comments
Post a Comment