Level 2 | Algorithms | Lab 5
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works similarly to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an unsorted
part. Values from the unsorted part are picked and placed in the correct position in
the sorted part.
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Insertion Sort Algorithm:
Step 1: If it is the first element, it is already sorted.
Step 2: Pick the next element.
Step 3: Compare with all the elements in sorted sub-list.
Step 4: Shift all the elements in sorted sub-list that is greater than the value to be sorted.
Step 5: Insert the value.
Step 6: Repeat until list is sorted.
1|Page
Modern Academy - Eng. Noha Ali
Level 2 | Algorithms | Lab 5
Insertion Sort Code:
package insertionsort;
import [Link];
public class InsertionSort {
public static void Sort(int arr[])
{
int i,j,key;
for (i=1 ; i<[Link]; i++)
{
key=arr[i];
j=i-1;
while (j>=0 && key<arr[j])
{
arr[j+1] = arr[j];
j--;
}
arr[j+1]=key;
}
}
public static void main(String[] args) {
int arr_size;
Scanner s = new Scanner([Link]);
[Link]("Enter Array Size");
arr_size=[Link]();
int [] arr= new int[arr_size];
[Link]("Enter array Elements to be sorted!");
for (int i=0;i<[Link]; i++)
{
arr[i]=[Link]();
}
//int arr[]={4,3,2,10,12,1,5,6};
Sort(arr);
[Link]("Array After Sorting");
for (int i=0; i <[Link] ; i++)
[Link](arr[i]);
}
}
2|Page
Modern Academy - Eng. Noha Ali
Level 2 | Algorithms | Lab 5
Time Complexity for Selection Sort Algorithm ∈ 𝑶(𝒏𝟐 ) in the worst case.
3|Page
Modern Academy - Eng. Noha Ali