Sorting rearranges data into a chosen order. The order may be numeric, lexicographic, or based on a custom key.
Sorting often turns a hard problem into an easier one because nearby values, smallest values, largest values, or ordered boundaries become visible.
Core Idea
Many algorithms become simpler after sorting because they can reason from left to right. Binary search, two pointers, greedy selection, duplicate grouping, and interval processing often depend on sorted order.
Comparison sorting usually has O(n log n) time complexity for efficient general-purpose algorithms.
Python Example
people = [("Mina", 17), ("Jin", 14), ("Ara", 17)]
by_age = sorted(people, key=lambda person: person[1])sorted returns a new list. list.sort() sorts a list in place.
Common Confusions
Sorting changes the problem structure, but it may also destroy original order. If original positions matter, store them before sorting.
Sorting is not always free. An O(n log n) preprocessing step may be worthwhile for many queries, but unnecessary for a single simple scan.
When To Use It
Use sorting when relative order reveals useful structure: finding close values, grouping equal values, applying two pointers, choosing cheapest items, or preparing for binary search.