environment: python3.6, Anaconda 5.1, Jupyter notebook, numba.
I used a random array generated by Python to measure the time complexity of shell sort, but found that its time complexity is more in line with NlogN. I understand that the time complexity of shell sort is O(n^2), I am confused.
Shell sort code:
def shell_sort(list):
n = len(list)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = list[i]
j = i
while j >= gap and list[j - gap] > temp:
list[j] = list[j - gap]
j -= gap
list[j] = temp
gap = gap // 2
return list
O(n^2) is only the worst case time complexity, so the algorithm can run in less time than that on a random input and even on average (or even on almost all its inputs...).
Also the complexity of Shellsort depends on the "gap sequence" you selected.
Certain gap sequences result in a worst time case smaller than O(n^2), like O(n^1.5) for the gap sequence
1, 4, 13, 40, 121, ...
or even O(nlog^2(n)) for1, 2, 3, 4, 6, 8, 9, 12, ...
(both due to Pratt, 1971). In other words: just trying on one input is not significant at all and the claim about O(n^2) may be false depending on the exact implementation of the algorithm.