Javatpoint Logo
Javatpoint Logo

Insertion Sort

Insertion sort is the simple sorting algorithm which is commonly used in the daily lives while ordering a deck of cards. In this algorithm, we insert each element onto its proper place in the sorted array. This is less efficient than the other sort algorithms like quick sort, merge sort, etc.

Technique

Consider an array A whose elements are to be sorted. Initially, A[0] is the only element on the sorted set. In pass 1, A[1] is placed at its proper index in the array.

In pass 2, A[2] is placed at its proper index in the array. Likewise, in pass n-1, A[n-1] is placed at its proper index into the array.

To insert an element A[k] to its proper index, we must compare it with all other elements i.e. A[k-1], A[k-2], and so on until we find an element A[j] such that, A[j]<=A[k].

All the elements from A[k-1] to A[j] need to be shifted and A[k] will be moved to A[j+1].

Complexity

Complexity Best Case Average Case Worst Case
Time Ω(n) θ(n2) o(n2)
Space o(1)

Algorithm

  • Step 1: Repeat Steps 2 to 5 for K = 1 to N-1
  • Step 2: SET TEMP = ARR[K]
  • Step 3: SET J = K ? 1
  • Step 4: Repeat while TEMP <=ARR[J]
    SET ARR[J + 1] = ARR[J]
    SET J = J ? 1
    [END OF INNER LOOP]
  • Step 5: SET ARR[J + 1] = TEMP
    [END OF LOOP]
  • Step 6: EXIT

C Program

Output:

Printing Sorted Elements . . . 
7
9
10
12
23
23
34
44
78 
101 

C++ Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

Java Program

Output:

Printing sorted elements . . . 
7
9
10
12
23
23
34
44
78 
101 

C# Program

Output:

printing sorted elements . . . 
7
9
10
12
23
23
34
44
78 
101 

Python Program

Output:

printing sorted elements . . . 
7
9
10
12
23
23
34
44
78 
101 

Swift Program

Output:

printing sorted elements...

7
9
10
12
23
23
34
44
78
101

JavaScript Program

Output:

printing sorted elements ...
7
9
10
12
23
23
34
44
78
101

PHP Program

Output:

printing sorted elements ...
7
9
10
12
23
23
34
44
78
101

Next TopicMerge Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA