Lec6 Quick-Merge Sort
Lec6 Quick-Merge Sort
( sorting algorithms)
LECTURE 06
BY ENGR. SEEMA BUGHIO
Roughly Comparison
What Is Sorting?
What Is Sorting?
Internal/External Sorting
Divide and conquer approach
Divide and conquer approach
Binary Search
Quick Sort
Merge Sort
Quick Sort Algorithms
Best-case: O(n log n)
This occurs when the pivot is always the median element, dividing the array into
two halves of roughly equal size.
In the best case, the recurrence tree is a balanced binary tree, resulting in a
logarithmic time complexity.
Worst-case: O(n^2)-
This occurs when the pivot is always the smallest or largest element in the array, causing the
recursive calls to sort sub arrays of size n-1, n-2, ..., 1.
Example:
Already sorted or reverse-sorted array.
In the worst case, the recurrence tree is a linear chain, leading to a quadratic time complexity
Scenarios Where Quicksort Is A Good
Choice
1. Large datasets: QuickSort is efficient for sorting large datasets, as it has an average-case
time complexity of O(n log n).
2. Randomly ordered data: QuickSort performs well on randomly ordered data, as it's less
prone to worst-case scenarios.
3. Memory constraints: QuickSort is an in-place sorting algorithm, meaning it doesn't
require extra memory to sort the data.
4. Average-case scenarios: QuickSort is a good choice when the data is likely to be in a
random order, as it's optimized for average-case scenarios.
Merge sort
Example
Example
Example
Let’s Understand This…!
Time complexity
Add these…..
Pros:- Cons:-
For large dataset because n*logn complexity Need Extra space.
in all cases. Not in-place sorting.
Stable.
Quick Vs Merge Sort
both Merge Sort and Quick Sort have a time complexity that is independent of the size of the
input, making them scalable algorithms.
Merge Sort: O(n log n)
Quick Sort (average case): O(n log n)
This means that as the input size (n) increases, the time taken to sort the data grows
logarithmically, which is a relatively slow growth rate.
This makes both algorithms efficient for large datasets.
However, it's important to note that Quick Sort has a worst-case time complexity of O(n^2),
which can occur in specific scenarios (e.g., when the input is already sorted or reverse-sorted).
In contrast, Merge Sort has a guaranteed time complexity of O(n log n) in all cases.
Merge Sort Is Still Preferred
However, there are some reasons why Merge Sort is still preferred in some situations:
1. Stability: Merge Sort is a stable sorting algorithm, meaning it preserves the order of equal
elements. This is important in certain applications where the order of equal elements matters.
2. Predictable performance: Merge Sort has a guaranteed time complexity of O(n log n) in
all cases, making it a reliable choice for critical applications.
3. Simple implementation: Merge Sort has a relatively simple implementation, especially
when compared to other efficient sorting algorithms like Quick Sort.
Thank You