Professional Documents
Culture Documents
Using Array
Presented by Zahir Ullah
What is algorithm?
For I =1 since 22 is smaller than 25, move 25 and insert 22 before 25.
(22,25,27,15,9)
For I =2, 27 will remain at its position as all elements in array are smaller than 27.
(22,25,27,15,19)
For I =3,15 will move to the beginning and all other elements from 22 to 27 will
move On position to the right:
(15,22,25,27,19)
For I =4,19 will move to position after 15 and element from 22 to 27 will move
one To the right
(15,19,22,25,27)
Implementation
Pseudo Code
Counter1 assign zero;
for( counter=0;counter<6;counter++)
counter2=counter1;
for(counter_inner=counter1;counter_inner>0;counter_inner--)
if(a[counter_inner-1]>a[counter2])
temp=array[counter2];
a[counter2]=a[counter_inner-1];
a[counter_inner-1]=temp;
--counter2;
Counter1++;
Let’s see the output
complexity
•Best Case Complexity - It occurs when there is no sorting required, i.e. the array
is already sorted. The best-case time complexity of insertion sort is O(n) and
swapping O(1).
15,19,22,25,27
•Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average case
time complexity of insertion sort is O(n2) and swapping.
n(n-1)/2 n2-n/2 dominant term O(n2)
22,19,15,25,27
•Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements in
ascending order, but its elements are in descending order. The worst-case time
complexity of insertion sort is O(n2) and swapping.
27,25,22,19,15
Algorithm analysis
Space complexity
The space complexity of insertion sort is O(1). It is
because, in insertion sort, an extra variable is
required
Space Complexity for swapping.
O(1)
Stable YES
Stable:
1,3,5a,6,5b,8
5b will remain in right side