160 likes | 175 Views
Learn about Divide and Conquer methods like Merge Sort and Quick Sort, with analysis and improvements for optimal efficiency. Also explore Binary Search for faster retrieval in sorted arrays.
E N D
Divide and Conquer 1.) A problem’s instance is divides into several smaller instances of the same problem, ideally of about the same size. 2.) The smaller instance are solved(typically recursively , though sometimes a different algorithm is employed when instances become small enough) 3.) If necessary, the solutions obtained for the smaller instances are combined to get a solution to the original instance.
Merge sort • Split array A[0..n-1] into about equal halves and make copies of each half in arrays B and C • Sort arrays B and C recursively • Merge sorted arrays B and C into array A as follows: • Repeat the following until no elements remain in one of the arrays: • compare the first elements in the remaining unprocessed portions of the arrays • copy the smaller of the two into A, while incrementing the index indicating the unprocessed portion of that array • Once all elements in one of the arrays are processed, copy the remaining unprocessed elements from the other array into A.
p A[i]p A[i]p Quicksort • Select a pivot (partitioning element).(Here is first) • Rearrange the list so that all the elements in the first s positions are smaller than or equal to the pivot and all the elements in the remaining n-s positions are larger than or equal to the pivot. • Exchange the pivot with the last element in the first (i.e., )subarray — the pivot is now in its final position • Sort the two subarrays recursively
Quicksort Example 5 3 1 9 8 2 4 7 2 3 1 4 5 8 9 7 1 2 3 4 5 7 8 9 123 4 5789 123 4 5789 12345789
Analysis of Quicksort • Best case: split in the middle — Θ(n log n) • Worst case: sorted array! — Θ(n2) • Average case: random arrays —Θ(n log n) • Improvements: • better pivot selection: median of three partitioning • switch to insertion sort on small subfiles • elimination of recursion These combine to 20-25% improvement
Binary Search • If we place our items in an array and sort them in either ascending or descending order on the key first, then we can obtain much better performance with an algorithm called binary search. • In binary search, we first compare the key with the item in the middle position of the array. If there's a match, we can return immediately. If the key is less than the middle key, then the item sought must lie in the lower half of the array; if it's greater then the item sought must lie in the upper half of the array. So we repeat the procedure on the lower (or upper) half of the array.