|
| 1 | +# Sort and Search |
| 2 | + |
| 3 | +When sorting and searching items in data structures, efficiency is key. |
| 4 | + |
| 5 | +| Algorithm | Best case | Average case | Worst case | Space complexity | |
| 6 | +| ------------------ | -------------- | -------------- | -------------- | ----------------------------- | |
| 7 | +| **Insertion sort** | O(n) | O(n²) | O(n²) | O(1) | |
| 8 | +| **Selection sort** | O(n²) | O(n²) | O(n²) | O(1) | |
| 9 | +| **Bubble sort** | O(n) | O(n²) | O(n²) | O(1) | |
| 10 | +| **Merge sort** | O(n log n) | O(n log n) | O(n log n) | O(n) | |
| 11 | +| **Quicksort** | O(n log n) | O(n log n) | O(n²) | O(log n) (avg) / O(n) (worst) | |
| 12 | +| **Heapsort** | O(n log n) | O(n log n) | O(n log n) | O(1) | |
| 13 | +| **Counting sort** | O(n + k) | O(n + k) | O(n + k) | O(n + k) | |
| 14 | +| **Bucket sort** | O(n + k) | O(n + k) | O(n²) | O(n + k) | |
| 15 | +| **Radix sort** | O(d ⋅ (n + k)) | O(d ⋅ (n + k)) | O(d ⋅ (n + k)) | O(n + k) | |
| 16 | + |
| 17 | +## Fundamental Concepts for Sorting Algorithms |
| 18 | + |
| 19 | +- **Counting sort**: `k` represents the range of values in the input array. |
| 20 | +- **Bucket sort**: `k` represents the number of buckets used. |
| 21 | +- **Radix sort**: `k` represents the range of inputs, and `d` represents the number of digits in the maximum element. |
| 22 | + |
| 23 | +--- |
| 24 | + |
| 25 | +### Key Sorting Properties |
| 26 | + |
| 27 | +- **Stability**: A sorting algorithm is stable if it preserves the relative order of equal elements in the sorted output. If two elements have equal values, their order remains unchanged. |
| 28 | +- **In-place sorting**: An in-place sorting algorithm sorts the elements within the original data structure, using only a constant amount of extra storage. |
| 29 | +- **Comparison-based sorting**: These algorithms sort elements by comparing them pairwise, typically having a lower bound of **O(n log n)**. Non-comparison-based sorting algorithms can achieve linear time complexity but require specific assumptions about the input data. |
| 30 | + |
| 31 | +--- |
| 32 | + |
| 33 | +### Real-Word Example |
| 34 | + |
| 35 | +Sorting products by category: When users search for products, the platform often sorts the results based on various criteria such as lowest to highest price, highest to lowest rating, or even relevance to the search query. Efficient sorting algorithms ensure large datasets of products can be quickly arranged according to user preferences. |
0 commit comments