Download Insertion-Sort

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Insertion Sort is an efficient algorithm for sorting a small number of elements. It is similar to sort a
hand of playing cards.
Playing a card is one of the techniques of sorting and in Insertion Sort we follow following steps.
-
Start with an empty left hand and cards face down on the table.
-
Then remove one card at a time from the table and Insert it into the correct position in
the left hand.
-
To find a correct position for a card, we compare it with each of the cards already in the
hand from right to left.
Input : A sequence of n numbers a1, a2, ..., an.
Output : A permutation (reordering) of the input sequence such that a1<=a2<=a3<=….an
The numbers that we wish to sort are also known as Keys. Although conceptually we are sorting a
sequence, then input comes to us in the form of an array with n elements.
Pseudocode of Insertion Sort
INSERTION-SORT(A)
1. for j = 2 to n
2.
key ← A [j]
3.
// Insert A[j] into the sorted sequence A[1..j-1]
4.
j←i–1
5.
while i > 0 and A[i] > key
6.
A[i+1] ← A[i]
7.
i←i–1
8.
A[j+1] ← key