Sorting in Data Structures
1️⃣ What is Sorting?
Sorting is the process of arranging elements in a particular order (ascending or descending). It helps in efficient searching, data retrieval, and processing.
2️⃣ Types of Sorting Algorithms
Sorting algorithms are mainly categorized into:
- Comparison-based Sorting (Bubble Sort, Selection Sort, Quick Sort, Merge Sort, etc.)
- Non-comparison Sorting (Counting Sort, Radix Sort, Bucket Sort, etc.)
3️⃣ Common Sorting Algorithms
Algorithm | Best Case | Worst Case | Average Case | Space Complexity | Stable? |
---|---|---|---|---|---|
Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ Yes |
Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | ❌ No |
Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ Yes |
Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | ✅ Yes |
Quick Sort | O(n log n) | O(n²) | O(n log n) | O(log n) | ❌ No |
Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | ❌ No |
Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | ✅ Yes |
Radix Sort | O(nk) | O(nk) | O(nk) | O(n + k) | ✅ Yes |
4️⃣ Sorting Algorithm Implementations in C
✅ 1. Bubble Sort (Simple but Inefficient)
Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order.
✅ Simple but slow (O(n²))
❌ Not suitable for large datasets
✅ 2. Insertion Sort (Efficient for Small Datasets)
Insertion Sort builds a sorted array one item at a time.
✅ Good for small datasets (O(n²))
✅ Performs well when data is nearly sorted
✅ 3. Merge Sort (Efficient, Uses Divide & Conquer)
Merge Sort divides the array into two halves, sorts them, and merges them.
✅ Efficient (O(n log n))
❌ Uses extra memory (O(n))
✅ 4. Quick Sort (Best for Large Datasets)
Quick Sort picks a pivot, partitions the array, and recursively sorts both halves.
✅ Fastest in practice (O(n log n) average case)
❌ Worst-case O(n²) if poorly implemented
No comments:
Post a Comment