Sorting is the process of arranging elements in a specific order (usually ascending or descending). It's one of the most fundamental operations in computer science and appears everywhere: from displaying search results to optimizing database queries.
Why Sorting Matters
Enables binary search: Sorted data can be searched in O(log n) instead of O(n)
Simplifies problems: Many problems become easier once data is sorted (finding duplicates, merging lists, etc.)
Data presentation: Users expect sorted results (alphabetical lists, ranked items)
Foundation for other algorithms: Many algorithms assume sorted input
Key Properties
When choosing a sorting algorithm, consider these properties:
Property
Description
Time Complexity
How runtime grows with input size (best, average, worst case)
Space Complexity
Extra memory needed beyond the input array
Stability
Whether equal elements maintain their relative order
In-place
Whether it sorts using only O(1) extra space
Adaptive
Whether it runs faster on partially sorted data
What is Stability?
A stable sort preserves the relative order of elements with equal keys. This matters when sorting by multiple criteria.Example: Sorting students by grade while keeping alphabetical order within each grade requires a stable sort.
Before
Stable Sort
Unstable Sort
(Alice, B)
(Alice, A)
(Alice, A)
(Bob, A)
(Bob, A)
(Charlie, A)
(Charlie, A)
(Charlie, A)
(Bob, A)
(Alice, A)
(Alice, B)
(Alice, B)
Notice how stable sort keeps Bob before Charlie (original order), while unstable sort may swap them.