0% found this document useful (0 votes)
6 views15 pages

Insertion Sort

The document describes the insertion sort algorithm, which sorts an array by repeatedly selecting an element and placing it in the correct position relative to previously sorted elements. It includes a code implementation and outlines the algorithm's steps, as well as its best and worst-case time complexities. The best-case complexity is O(n) and the worst-case complexity is O(n²).

Uploaded by

shivendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Insertion Sort

The document describes the insertion sort algorithm, which sorts an array by repeatedly selecting an element and placing it in the correct position relative to previously sorted elements. It includes a code implementation and outlines the algorithm's steps, as well as its best and worst-case time complexities. The best-case complexity is O(n) and the worst-case complexity is O(n²).

Uploaded by

shivendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Code insertionSort(int a[], int n)

{
int i, key, j;
for (i = 1; i < n; i++)
{
key = a[i];
j = i - 1;

while (j >= 0 && a[j] > key)


{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
Algorithm
Start
Start a for loop till it reaches ‘n’
Select the ith element from the array and
assign it to key
Compare the key with the i-1 element in the
array
If it is greater then swap the ith element and
i-1 element. Then decrement i.
If it is not greater continue with for loop and
change the key.
Repeat the above 4 steps till for loop fails
8 2 4 9 3 6
8 2 4 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6

2 4 8 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6

2 4 8 9 3 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6

2 4 8 9 3 6

2 3 4 8 9 6
8 2 4 9 3 6

2 8 4 9 3 6

2 4 8 9 3 6

2 4 8 9 3 6

2 3 4 8 9 6
Best case complexity : O(n)
Worst case complexity : O(n2)

You might also like