Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Insertion Sort

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

Insertion Sort

Insertion Sort
0 1 2 3 4
36 10 85 14 45
Insertion Sort
0 1 2 3 4
36 10 85 14 45

0 1 2 3 4
36 85 14 45
y
10
Insertion Sort

0 1 2 3 4
36 85 14 45
y
10

0 1 2 3 4 y
36 85 14 45
10
Insertion Sort

0 1 2 3 4 y
10 36 85 14 45

0 1 2 3 4 y
10 36 85 14 45
Insertion Sort

0 1 2 3 4 y
10 36 14 45 85

0 1 2 3 4 y
10 36 14 45 85
Insertion Sort

0 1 2 3 4 y
10 36 85 14 45

0 1 2 3 4 y
10 36 85 14 45
Insertion Sort

0 1 2 3 4 y
10 36 85 45 14

0 1 2 3 4 y
10 36 85 45 14
Insertion Sort

0 1 2 3 4 y
10 36 85 45 14

0 1 2 3 4 y
10 36 85 45 14
Insertion Sort

0 1 2 3 4 y
10 36 85 45 14

0 1 2 3 4 y
10 36 85 45 14
Insertion Sort

0 1 2 3 4 y
10 14 36 85 45

0 1 2 3 4 y
10 14 36 85 45
Insertion Sort

0 1 2 3 4 y
10 14 36 85 45

0 1 2 3 4 y
10 14 36 85 45
Insertion Sort

0 1 2 3 4 y
10 14 36 85 45

0 1 2 3 4 y
10 14 36 85 45
Insertion Sort

0 1 2 3 4 y
10 14 36 85 45

0 1 2 3 4 y
10 14 36 45 85
Insertion Sort
void insertsort(int x[], int n)
{
int i,k,y;
/* initially x[0] may be thought of as a sorted file of one element.
After each repetition of the following loop, the element x[0]
through x[k] are in order */
for (k = 1; k<n; k++)
{
/* y is a temporary location to store kth element */
y = x[k];
Insertion Sort
for (i = k-1; i>=0 && y < x[i]; i--)
{ x[i + 1] = x[i]; }
/* Insert y at proper position */
x [i + 1] = y;
} }

The time complexity is O(n2)

You might also like