Mergesort. Merging two sorted arrays To merge two sorted arrays into a third (sorted) array, repeatedly compare the two least elements and copy the smaller.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Back to Sorting – More efficient sorting algorithms.
CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
Garfield AP Computer Science
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
QuickSort The content for these slides was originally created by Gerard Harrison. Ported to C# by Mike Panitz.
CMPS1371 Introduction to Computing for Engineers SORTING.
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
Quicksort Divide-and-Conquer. Quicksort Algorithm Given an array S of n elements (e.g., integers): If array only contains one element, return it. Else.
CS 171: Introduction to Computer Science II Quicksort.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Introduction to Sorting
Faster Sorting Methods Chapter 9. 2 Chapter Contents Merge Sort Merging Arrays Recursive Merge Sort The Efficiency of Merge Sort Merge Sort in the Java.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Sorting21 Recursive sorting algorithms Oh no, not again!
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
Chapter 7: Sorting Algorithms
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Unit 281 Merge- and Quick Sort Merge Sort Quick Sort Exercises.
Quicksort.
C++ Plus Data Structures
Quicksort
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Cmpt-225 Sorting – Part two. Idea of Quick Sort 1) Select: pick an element 2) Divide: partition elements so that x goes to its final position E 3) Conquer:
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Joseph Lindo Sorting Algorithms Sir Joseph Lindo University of the Cordilleras.
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
ALGORITHM ANALYSIS AND DESIGN INTRODUCTION TO ALGORITHMS CS 413 Divide and Conquer Algortihms: Binary search, merge sort.
Introduction to Sorting. What is Sorting? Sorting: an operation that segregates items into groups according to specified criterion. A = {
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
1 Designing algorithms There are many ways to design an algorithm. Insertion sort uses an incremental approach: having sorted the sub-array A[1…j - 1],
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
The Selection Problem. 2 Median and Order Statistics In this section, we will study algorithms for finding the i th smallest element in a set of n elements.
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
© 2006 Pearson Addison-Wesley. All rights reserved10 B-1 Chapter 10 (continued) Algorithm Efficiency and Sorting.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Sort Algorithms.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Searching and Sorting Recursion, Merge-sort, Divide & Conquer, Bucket sort, Radix sort Lecture 5.
Sorting CS Sorting means... Sorting rearranges the elements into either ascending or descending order within the array. (we’ll use ascending order.)
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Sorting – Part II CS 367 – Introduction to Data Structures.
QUICKSORT 2015-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Fast Sorting COMP
Sorting and Searching Algorithms CS Sorting means... l The values stored in an array have keys of a type for which the relational operators are.
Merge Sort. In plain English: if the size of the array > 1, split the array into two halves, and recursively sort both halves; when the sorts return,
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Nothing is particularly hard if you divide it into small jobs. Henry Ford Nothing is particularly hard if you divide it into small jobs. Henry Ford.
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
FASTER SORT using RECURSION : MERGE SORT COMP 103.
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Fundamentals of Algorithms MCS - 2 Lecture # 11
Introduction to Sorting
Introduction to Sorting
Warmup What is an abstract class?
Quicksort 1.
CS 3343: Analysis of Algorithms
Advanced Sorting Methods: Shellsort
Merge sort merge sort: Repeatedly divides the data in half, sorts each half, and combines the sorted halves into a sorted whole. The algorithm: Divide.
Chapter 4.
Merge sort merge sort: Repeatedly divides the data in half, sorts each half, and combines the sorted halves into a sorted whole. The algorithm: Divide.
Core Assessments Core #1: This Friday (5/4) Core #2: Tuesday, 5/8.
Presentation transcript:

Mergesort

Merging two sorted arrays To merge two sorted arrays into a third (sorted) array, repeatedly compare the two least elements and copy the smaller of the two

Merging parts of a single array The procedure really is no different if the two “arrays” are really portions of a single array first part second part

Sorting an array If we start with an array in which the left half is sorted and the right half is sorted, we can merge them into a single sorted array We need to copy our temporary array back up This is a sorting technique called mergesort

Recursion How did the left and right halves of our array get sorted? Obviously, by mergesorting them To mergesort an array: –Mergesort the left half –Mergesort the right half –Merge the two sorted halves Each recursive call is with a smaller portion of the array The base case: Mergesort an array of size 1

The actual code private void recMergeSort(long[] workspace, int lowerBound, int upperBound) { if (lowerBound == upperBound) return; int mid = (lowerBound + upperBound) / 2; recMergeSort(workspace, lowerBound, mid); recMergeSort(workspace, mid + 1, upperBound); merge(workspace, lowerBound, mid + 1, upperBound); } from Lafore, p. 287

The merge method The merge method is too ugly to show It requires: –The index of the first element in the left subarray –The index of the last element in the right subarray –The index of the first element in the right subarray That is, the dividing line between the two subarrays –The index of the next value in the left subarray –The index of the next value in the right subarray –The index of the destination in the workspace But conceptually, it isn’t difficult!

Analysis of the merge operation The basic operation is: compare two elements, move one of them to the workspace array –This takes constant time We do this comparison n times –Hence, the whole thing takes O(n) time Now we move the n elements back to the original array –Each move takes constant time –Hence moving all n elements takes O(n) time Total time: O(n) + O(n) = O(n)

But wait...there’s more So far, we’ve found that it takes O(n) time to merge two sorted halves of an array How did these subarrays get sorted? At the next level down, we had four subarrays, and we merged them pairwise Since merging arrays is linear time, when we cut the array size in half, we cut the time in half But there are two arrays of size n/2 Hence, all merges combined at the next lower level take the same amount of time as a single merge at the upper level

Analysis II So far we have seen that it takes –O(n) time to merge two subarrays of size n/2 –O(n) time to merge four subarrays of size n/4 into two subarrays of size n/2 –O(n) time to merge eight subarrays of size n/8 into four subarrays of size n/4 –Etc. How many levels deep do we have to proceed? How many times can we divide an array of size n into two halves? –log 2 n, of course

Analysis III So if our recursion goes log n levels deep......and we do O(n) work at each level......our total time is: log n * O(n)......or in other words, O(n log n) For large arrays, this is much better than Bubblesort, Selection sort, or Insertion sort, all of which are O(n 2 ) Mergesort does, however, require a “workspace” array as large as our original array

Stable sort algorithms A stable sort keeps equal elements in the same order This may matter when you are sorting data according to some characteristic Example: sorting students by test scores Bob Ann Joe Zöe Dan Pat Sam original array Bob Ann Joe Zöe Dan Pat Sam stably sorted

Unstable sort algorithms An unstable sort may or may not keep equal elements in the same order Stability is usually not important, but sometimes it matters Bob Ann Joe Zöe Dan Pat Sam original array Bob Ann Joe Zöe Dan Pat Sam unstably sorted

Is mergesort stable? private void recMergeSort(long[] workspace, int lowerBound, int upperBound) { if (lowerBound == upperBound) return; int mid = (lowerBound + upperBound) / 2; recMergeSort(workspace, lowerBound, mid); recMergeSort(workspace, mid + 1, upperBound); merge(workspace, lowerBound, mid + 1, upperBound); } Is this sort stable? recMergeSort does none of the actual work of moving elements around—that’s done in merge

Stability of merging Stability of mergesort depends on the merge method After all, this is the only place where elements get moved What if we encounter equal elements when merging? –If we always choose the element from the left subarray, mergesort is stable

The End