Uploaded by wegepi9592

Insertion sort

advertisement
Insertion sort
===========
To sort an array of size n in ascending order:
1) Iterate from arr[1] to arr[n] over the array
2) Compare the current element (Key) to its predecessor
3) If the key element is smaller than its predecessor , compare it to the elements before . Move
the greater elements one position up to make space for the swapped element
Arr ➔
0
5
1
4
2
10
3
1
4
6
5
2
0
4
4
4
4
1
1
1
1
1
1
5
5
5
5
4
4
4
4
2
2
10
?
10
10
5
5
5
5
4
3
1
1
1
?
10
10
6
6
5
4
6
6
6
6
6
?
10
10
6
5
2
2
2
2
2
2
2
?
10
Temp: 4
For(i=1;I<n;i++)
{
Temp=arr[i];
J=i-1;
// shifting
While(j>=0&& arr[j]>temp)
{
Arr[j+1]=arr[j]
j--;
}
//insert
Arr[j+1]=temp;
}
O(n2)
Download