1 / 10

CS 162 Intro to Programming II

CS 162 Intro to Programming II. MergeSort. MergeSort. Suppose you have 2 sorted arrays How do you merge them into a sorted array? Just look at the first element in both arrays Put the smaller element into the new array.

Download Presentation

CS 162 Intro to Programming II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 162Intro to Programming II MergeSort

  2. MergeSort • Suppose you have 2 sorted arrays • How do you merge them into a sorted array? • Just look at the first element in both arrays • Put the smaller element into the new array. • Then look at the next element in the array that the smaller element came from and compare with the current element in the other array • Repeat… 4 15 8 16 42 23

  3. Merging 4 4 4 15 4 15 4 4 15 4 15 8 16 8 16 8 16 16 8 8 8 42 23 42 23 23 42 23 42 15

  4. Merging 15 4 16 15 16 4 4 15 4 16 4 4 16 8 23 16 8 16 23 8 8 8 8 42 23 15 42 23 15 23 15 42 42 The complexity of merge sort is O(n)

  5. MergeSort • But wait a second…you aren’t given two already sorted arrays • Recursion to the rescue! • Keep dividing the array in half (until the subarraysize is 1) • Asubarray of size 1 is sorted • Merge the sorted halves together

  6. MergeSort Illustrated 3 1 7 4 2 2 5 6 2 6 6 7 5 7 1 5 2 3 2 1 3 2 4 4 5 4 1 2 3 6 2 7

  7. MergeSort Illustrated 3 1 7 4 2 2 5 6 6 7 6 7 2 3 1 1 4 2 2 4 5 3 5 2 2 4 1 2 3 6 5 7

  8. Complexity • Each recursive call operates on an array that is half the size of the original array • How many level’s to get to arrays size of 1? About O(log n)

  9. Complexity • Each recursive call operates on an array that is half the size of the original array • Each time you do a sort() you do a merge which is O(n). Each level is O(n).

  10. Complexity O(n) O(n) O(n) For O(log n) levels Total complexity is O(n log n) Best and worst case

More Related