Sorting Algorithms Explained with Examples
Bubble Sort
Concept: Repeatedly swaps adjacent elements if they are in the wrong order.
Time: O(n^2), Best: O(n), Space: O(1)
Use: Educational purposes.
Example: def bubble_sort(arr): ...
Selection Sort
Concept: Selects the minimum element and places it at the beginning.
Time: O(n^2), Space: O(1)
Use: Few writes needed.
Example: def selection_sort(arr): ...
Insertion Sort
Concept: Builds sorted list by inserting elements into correct position.
Time: O(n^2), Best: O(n), Space: O(1)
Use: Small or partially sorted arrays.
Example: def insertion_sort(arr): ...
Merge Sort
Concept: Divide and merge recursively.
Time: O(n log n), Space: O(n)
Use: Large, stable sorting.
Example: def merge_sort(arr): ...
Quick Sort
Concept: Partition with pivot.
Time: O(n log n), Worst: O(n^2), Space: O(log n)
Use: Fast for large datasets.
Example: def quick_sort(arr): ...
Heap Sort
Concept: Builds a heap then extracts elements.
Time: O(n log n), Space: O(1)
Use: Priority queues.
Example: def heap_sort(arr): ...
Counting Sort
Concept: Count occurrences and rebuild array.
Time: O(n + k), Space: O(k)
Use: Small integer keys.
Example: def counting_sort(arr): ...
Sorting Algorithms Explained with Examples
Radix Sort
Concept: Sort by digit position using counting sort.
Time: O(nk), Space: O(n + k)
Use: Large integers.
Example: def radix_sort(arr): ...
Bucket Sort
Concept: Divide array into buckets and sort.
Time: O(n + k), Space: O(n)
Use: Uniformly distributed floating numbers.
Example: def bucket_sort(arr): ...
Shell Sort
Concept: Insertion sort with decreasing gaps.
Time: O(n log^2 n), Space: O(1)
Use: Medium datasets.
Example: def shell_sort(arr): ...
Tim Sort
Concept: Hybrid of merge and insertion sort.
Time: O(n log n), Best: O(n)
Use: Python's built-in sorted().
Example: sorted(arr)