I have a random ordered array of 30 elements with only 3 distinct keys (TRUE, FALSE and NULL) that I want to sort using insertion sort. What will be the time complexity? Will it be O(n2) assuming worst case or O(n) assuming best case since there are only 3 different keys?
I have a random ordered array of 30 elements with only 3 distinct keys
Share
n refers to the size of the array, not the possible elements of the array. Thus, the complexity is the same:
Having 3 distinct elements will reduce the amount of elements you have to check during the “insertion” phase, but only by a constant factor. This will not change the asymptotic run-time.
For example, in the average-case, instead of insert checking n elements, it will check n/3 elements. This is better, but not asymptotically.