Sorting arranges data in a specific order. Different algorithms have different trade-offs.
Introduction to CS
What is Computer Science?
Operating Systems
OS Fundamentals
Cybersecurity Basics
Security Fundamentals
Software Engineering
Software Development Life Cycle
Cloud Computing
Cloud Computing Basics
Dynamic Programming
Dynamic Programming Introduction
AI & Machine Learning
Introduction to AI & ML
Internet of Things
IoT Fundamentals
Blockchain Basics
How Blockchain Works
Computer Science
Beginner
FREE
Sorting Algorithms
Lesson 2 of 17
Beginner
Interactive
Syntax
COMPUTER-SCIENCE
Bubble Sort: O(n²) — simple, slow Selection Sort: O(n²) — simple, in-place Insertion Sort: O(n²) — good for small data Merge Sort: O(n log n) — stable, consistent Quick Sort: O(n log n) avg — fast in practice
Bubble Sort and Quick Sort
PYTHON
# Bubble Sort O(n^2) def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr # Quick Sort O(n log n) def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right) data = [64, 34, 25, 12, 22] print(f"Bubble: {bubble_sort(data.copy())}") print(f"Quick: {quick_sort(data.copy())}")
Practice
1
Exercise
Which sorting algorithm is most efficient for large datasets?
Answer
Merge Sort or Quick Sort — both O(n log n). Quick Sort is faster in practice.
Quick Quiz
1
What is the time complexity of Merge Sort?
Merge Sort consistently runs in O(n log n) time.
Interview Questions
When the dataset is small (n < 20) or nearly sorted. Insertion Sort has low overhead and is fast for small inputs.