This is a good opportunity to use binary search again (or just copy and paste & modify bisect.insort
, which I did):
def insort_case_insensitive(a, x): key = x.lower() lo, hi = 0, len(myList) while lo < hi: mid = (lo + hi) // 2 if key < a[mid].lower(): hi = mid else: lo = mid + 1 a.insert(lo, x)
Demo:
myList = ['a', 'b', 'c', 'd', 'e'] for x in 'A', 'B', 'C', 'D', 'E': insort_case_insensitive(myList, x) print myList
Print
['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E']
This is O (n), just like append + sort will, but only because of a.insert(lo, x)
at the end. Which is dead-simple and made in C, so it is very fast. Binary search, of course, only takes O (log n) steps, so it's super fast as well. The append + sort method will call .lower()
for all elements and compare them, both of which are much slower. @MoinuddinQuadri the first solution is also much slower due to calling .lower()
for all elements.
See my other answer for a comparative comparison.