Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.

Similar presentations


Presentation on theme: "CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort."— Presentation transcript:

1 CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort

2 Advanced Sorting We’ve learned some simple sorting methods, which all have quadratic costs ▫Easy to implement but slow Some advanced sorting methods that are much faster: ▫Merge Sort ▫Quick Sort

3 Merge Sort Divide and conquer Uses recursion Much faster than simple sorting algorithms Requires additional memory space ▫In fact, it requires a temporary array that’s as large as the original array.

4 Merging Two Sorted Arrays A key step in mergesort Assume arrays A and B are already sorted. Merge them to array C, such as C contains all elements from A and B, and remains sorted.

5 Merge Sort mergesort is pretty simple: ▫Divide array in half ▫Sort each half (this step uses recursion!) ▫Merge the two sorted halves What’s the base case? ▫When you have only one element left.

6 Merge Sort This is a divide and conquer approach ▫Divide: Partition the original problem into two sub-problems; ▫Conquer: Use recursion to solve each sub- problem; ▫Combine: The results are then combined to solve the original problem.

7 Example

8 Quick Sort The most popular sorting algorithm. Divide and conquer. Uses recursion. Fast, and sort ‘in-place’ (i.e. does not require additional memory space)

9 Partition (Split) A key step in quicksort Given an input array, and a pivot value ▫Think of the pivot value as a threshold. Partition the array to two groups: all elements smaller than the pivot are on the left, and those larger than the pivot are on the right. Example: 42 89 63 12 94 27 78 3 50 36 pivot: 42


Download ppt "CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort."

Similar presentations


Ads by Google