Chapter 2
Chapter 2
The binary search algorithm uses the divide-and-conquer strategy to search through an
array.
This searching algorithms works only on an ordered list.
Merge sort uses divide and conquer strategy and its time complexity
is O(nlogn).
Algorithm:
1. Divide the array in to two halves.
2. Recursively sort the first n/2 items.
3. Recursively sort the last n/2 items.
4. Merge sorted items (using an auxiliary array).
Example: Sort the following list using merge sort algorithm.
Example: Sort the following list using merge sort algorithm.
Complexity Analysis of Merge Sort:
• Time Complexity:
• Best Case: O(n log n), When the array is already sorted or nearly sorted.
• Average Case: O(n log n), When the array is randomly ordered.
• Worst Case: O(n log n), When the array is sorted in reverse order.
Advantages of Merge Sort:
• Stability : Merge sort is a stable sorting algorithm, which means it maintains the
relative order of equal elements in the input array.
Quick sort is the fastest known algorithm. It uses divide and conquer
strategy and in the worst case its complexity is O (n2). But its expected
complexity is O(nlogn).
Algorithm:
1. Choose a pivot value (mostly the first element is taken as the pivot value)
2. Position the pivot element and partition the list so that:
✓ the left part has items less than or equal to the pivot value
✓ the right part has items greater than or equal to the pivot value
4. Recursively sort the left part
5. Recursively sort the right part
.
Selection Sort
Basic Idea:
Loop through the array from i=0 to n-1.
Select the smallest element in the array from i to n
Swap this value with value at position i.
Given array abc = 34 8 64 51 32 21
.
Analysis
How many comparisons?
(n-1)+(n-2)+...+1= O(n2 )
How many swaps?
n=O(n)
How much space?
In-place algorithm
Individual Assignment (10%)