POST 1 of 5 MorningDSAConcept
Python's sort is timsort. It's stable.
When you call sorted() or list.sort() in Python, you're invoking timsort — an algorithm specifically designed for real-world data. Three properties matter. O(n log n) worst case. Same as mergesort, heapsort, quicksort (on average). Asymptotically optimal for comparison-based sorting. O(n) on already-sorted or nearly-sorted data. This is timsort's special skill. Real data often has runs of already-sorted segments — timsort detects them and merges efficiently. On an already-sorted list, it's literally linear time. Stable. Equal keys retain their original relative order. This matters more than people realise. Why stability matters. Suppose you have a list of (city, score) pairs, and you want to sort first by city, then within each city by score descending. With stable sort — sort by score (descending) first. Then sort by city. Within each city, the original order (which is now score-descending) is preserved. Done in two passes. With unstable sort — second sort might disturb the score order within a city. You'd need a tuple key to do both at once, which is more code. Python guarantees timsort stability. Most other languages don't — C++ std::sort is unstable; you have to ask for std::stable_sort. Java's Arrays.sort on objects is stable; on primitives it's not. Knowing your language's default matters. A related guarantee — timsort is 'natural'. Reverse-sorted data is also fast (it detects descending runs and reverses them). Mostly-sorted with a few out-of-place elements is fast. For your code — sorted() and list.sort() are almost always the right answer. The few cases they're not: when you only need top-k (use heapq), when you need to maintain a sorted collection across many inserts (use sortedcontainers), when stability would actively bite you (rare, but exists in some specialised algorithms). Know what your sort does.
#DSA#Algorithms#Python#100DaysOfCode#CodingInterview#Sorting