Data Structure
Explain runtime complexities in terms of big-oh for the following scenarios:Â Â [2 + 2 = 4 points]
a.Insertion sort applied on an array where all values are equal.
b.Merge sort applied on a collection where the items are already sorted in opposite order.
Solution
a. Lets suppose array Arr[]={a,a,a,a}
Insertion Sort Algorithm
procedure insertionSort( Arr : array )
int i,j
int key
for i = 1 to length(A) inclusive do:
key = A[i]
j = i-1
while j >= 0 and Arr[j] > key do:
Arr[j+1] = A[j]
j = j -1
end while
Arr[j+1] = key
end for
end procedure
In insertion sort there is always a comparison of key with previous value in while loop(Arr[j] > key).
so if the key is not smaller than previous value then no inversion will happen and there will be only 1 comparison occurs.
As we have all elements equal so n-1 comparison will occur.
Complexity= O(n-1)~O(n)
.