CSE 341 Lecture 4 merge sort; basic efficiency issues Ullman 3.3 - 3.4 slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
Back to Sorting – More efficient sorting algorithms.
Advertisements

Garfield AP Computer Science
Linked Lists. 2 Merge Sorted Lists Write an algorithm that merges two sorted linked lists The function should return a pointer to a single combined list.
Divide and Conquer Sorting Algorithms
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Sorting II 1 An Introduction to Sorting.
Building Java Programs
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
ALGORITHM ANALYSIS AND DESIGN INTRODUCTION TO ALGORITHMS CS 413 Divide and Conquer Algortihms: Binary search, merge sort.
Building Java Programs Chapter 13 Searching reading: 13.3.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Lecture10: Sorting II Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
Week 6 - Monday.  What did we talk about last time?  Exam 1!  Before that:  Recursion.
Main Index Contents 11 Main Index Contents Building a Ruler: drawRuler() Building a Ruler: drawRuler() Merge Algorithm Example (4 slides) Merge Algorithm.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
1 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
Merge Sort: Taught By Example CO1406: Algorithms and Data Structures Module Lecturer: Dr. Nearchos Paspallis Week 10 Lab - Practice with Merge sort and.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Sorting: Advanced Techniques Smt Genap
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Contest Algorithms January 2016 Pseudo-code for divide and conquer, and three examples (binary exponentiation, binary search, and mergesort). 5. Divide.
 MergeSort is a sorting algorithm which is more on the advanced end.  It is very fast, but unfortunately uses up a lot of memory due to the recursions.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Recursion COMP x1 Sedgewick Chapter 5. Recursive Functions problems can sometimes be expressed in terms of a simpler instance of the same problem.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
Building Java Programs Chapter 13 Searching and Sorting Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Unit 8 Search, Sort, Recursion
Lecture 25: Searching and Sorting
Unit 8 Search, Sort, Recursion
Using recursion for Searching and Sorting
Fundamentals of Algorithms MCS - 2 Lecture # 11
COP 3503 FALL 2012 Shayan Javed Lecture 16
CSE 341 Lecture 5 efficiency issues; tail recursion; print
slides created by Marty Stepp and Hélène Martin
Adapted from slides by Marty Stepp and Stuart Reges
Adapted from slides by Marty Stepp and Stuart Reges
Adapted from slides by Marty Stepp and Stuart Reges
Adapted from slides by Marty Stepp and Stuart Reges
Based on slides created by Ethan Apter & Marty Stepp
Building Java Programs
slides adapted from Marty Stepp and Hélène Martin
Building Java Programs
CSE 341 Lecture 3 let expressions; pattern matching Ullman
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.
slides adapted from Marty Stepp
CSE 154 Sorting reading: 13.3, 13.4
Adapted from slides by Marty Stepp and Stuart Reges
QuickSort Previous slides based on ones by Ethan Apter & Marty Stepp
slides created by Marty Stepp
slides adapted from Marty Stepp
slides created by Marty Stepp and Ethan Apter
slides created by Marty Stepp
slides created by Marty Stepp
CSE 143 Sorting reading: 13.3, 13.4.
Building Java Programs Chapter 13
CSE 373: Data Structures and Algorithms
CSE 373 Data Structures and Algorithms
slides created by Marty Stepp and Hélène Martin
Building Java Programs
slides adapted from Marty Stepp
Lecture 21: Searching and Sorting
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.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Stacks, Queues, ListNodes
Presentation transcript:

CSE 341 Lecture 4 merge sort; basic efficiency issues Ullman slides created by Marty Stepp

2 Exercise Write a function mergeSort that accepts a list and uses the merge sort algorithm to produce a list with the same elements in non-decreasing order.  mergeSort([5,2,8,4,9,6]) produces [2,4,5,6,8,9] (a tricky recursive algorithm for us to practice...)

3 Merge sort merge sort: Repeatedly divides data in half, sorts each half, and combines the sorted halves into a sorted whole. The algorithm:  Divide the list into two roughly equal halves.  Sort the left half.  Sort the right half.  Merge the two sorted halves into one sorted list.  Often implemented recursively.  An example of a "divide and conquer" algorithm. –Invented by John von Neumann in 1945

4 Merge sort example index value merge split merge split merge split merge split split merge

5 Merging sorted halves

6 Merge halves code (Java) // Merges the left/right elements into a sorted result. // Precondition: left/right are sorted public static void merge(int[] result, int[] left, int[] right) { int i1 = 0; // index into left array int i2 = 0; // index into right array for (int i = 0; i < result.length; i++) { if (i2 >= right.length || (i1 < left.length && left[i1] <= right[i2])) { result[i] = left[i1]; // take from left i1++; } else { result[i] = right[i2]; // take from right i2++; }

7 Merge sort code 2 // Rearranges the elements of a into sorted order using // the merge sort algorithm (recursive). public static void mergeSort(int[] a) { if (a.length >= 2) { // split array into two halves int[] left = Arrays.copyOfRange(a, 0, a.length/2); int[] right = Arrays.copyOfRange(a, a.length/2, a.length); // sort the two halves mergeSort(left); mergeSort(right); // merge the sorted halves into a sorted whole merge(a, left, right); }

8 Suggested helpers Write a function split that accepts a list and produces a tuple of two lists representing its even and odd indexes.  split([12, ~3, 0, 19, 1]) produces ([12, 0, 1], [~3, 19]) Write a function merge that accepts two sorted lists and produces a new merged sorted list.  merge([4, 9, 11], [~3, 2, 10]) produces [~3, 2, 4, 9, 10, 11]

9 Helper solutions (* Splits a list into 2 sublists of its even/odd indexes. *) fun split([]) = ([], []) | split([x]) = ([x], []) | split(first :: second :: rest) = let val (l1, l2) = split(rest) in (first :: l1, second :: l2) end; (* Merges sorted L1 and L2 into a sorted whole. *) fun merge([], L2) = L2 | merge(L1, []) = L1 | merge(L1 as first1 :: rest1, L2 as first2 :: rest2) = if first1 < first2 then first1 :: merge(rest1, L2) else first2 :: merge(L1, rest2);

10 Merge sort solution (* Rearranges the elements of the given list to be in non-decreasing order using the merge sort algorithm. *) fun mergeSort([]) = [] | mergeSort([value]) = [value] | mergeSort(lst) = let val (left, right) = split(lst) in merge(mergeSort(left), mergeSort(right)) end;

11 Efficiency exercise Write a function called reverse that accepts a list and produces the same elements in the opposite order.  reverse([6, 2, 9, 7]) produces [7,9,2,6] Write a function called range that accepts a maximum integer value n and produces the list [1, 2, 3,..., n-1, n]. Produce an empty list for all numbers less than 1.  Example: range(5) produces [1,2,3,4,5]

12 Flawed solutions These solutions are correct; but they have a problem... fun reverse([]) = [] | reverse(first :: rest) = [first]; fun range(0) = [] | range(n) = range(n - [n];

13 Efficiency of operator val x = [2, 4, 7]; val y = [5, 3]; val a = 9 :: x; val z = y; The :: operator is fast:O(1)  simply creates a link from the first element to front of right operator is slow:O(n)  must walk/copy the left list and then append the right one  in a recursive function n times : function is O(n 2 ) 2 x 47 5 y 3 9 a 2 z 47

14 Fixing inefficient recursion How can we improve the inefficient range code? fun range(0) = [] | range(n) = range(n - [n];  Hint: with :: as much as possible.

15 Better solution fun range(n) = let fun helper(min, max) = if min = max then [min] else min :: helper(min + 1, max) in helper(1, n) end;

16 More about efficiency The fibonacci function we wrote previously is also inefficient, for a different reason.  It makes an exponential number of recursive calls.  Example: fibonacci(5) –fibonacci(4) –fibonacci(3) »fibonacci(2) »fibonacci(1) –fibonacci(2) –fibonacci(3) –fibonacci(2) –fibonacci(1)  How can we fix it to make fewer (O(n)) calls?

17 Iterative Fibonacci in Java // Returns the nth Fibonacci number. // Precondition: n >= 1 public static int fibonacci(int n) { if (n == 1 || n == 2) { return 1; } int curr = 1; // the 2 most recent Fibonacci numbers int prev = 1; // k stores what fib number we are on now for (int k = 2; k < n; k++) { int next = curr + prev; // advance to next prev = curr; // Fibonacci number curr = next; } return curr; }

18 Efficient Fibonacci in ML (* Returns the nth Fibonacci number. Precondition: n >= 1 *) fun fib(1) = 1 | fib(2) = 1 | fib(n) = let fun helper(k, prev, curr) = if k = n then curr else helper(k + 1, curr, prev + curr) in helper(2, 1, 1) end;