Introduction to Sorting - aloalgo.com

Introduction to Sorting

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:
PropertyDescription
Time ComplexityHow runtime grows with input size (best, average, worst case)
Space ComplexityExtra memory needed beyond the input array
StabilityWhether equal elements maintain their relative order
In-placeWhether it sorts using only O(1) extra space
AdaptiveWhether 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.
BeforeStable SortUnstable 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.

Categories of Sorting Algorithms

CategoryTimeAlgorithms
Simple / QuadraticO(n²)Bubble, Insertion, Selection
Efficient / ComparisonO(n log n)Merge, Quick, Heap
Linear / Non-comparisonO(n)Counting, Radix, Bucket
Note: O(n log n) is the theoretical lower bound for comparison-based sorting. Linear time sorts bypass this by not comparing elements directly.

Chapters

Learn each category of sorting algorithms in detail:
Was this helpful?
© 2026 aloalgo.com. All rights reserved.