Contest Algorithms January 2016 Pseudo-code for divide and conquer, and three examples (binary exponentiation, binary search, and mergesort). 5. Divide.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Introduction to Algorithms Quicksort
Back to Sorting – More efficient sorting algorithms.
Garfield AP Computer Science
Nov 10, Fall 2009IAT 8001 Binary Search Sorting. Nov 10, Fall 2009IAT 8002 Search  Often want to search for an item in a list  In an unsorted list,
Jun 23, 2014IAT 2651 Binary Search Sorting. Jun 23, 2014IAT 2652 Search  Frequently wish to organize data to support search –Eg. Search for single item.
CS4413 Divide-and-Conquer
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
ADA: 4. Divide/Conquer1 Objective o look at several divide and conquer examples (merge sort, binary search), and 3 approaches for calculating their.
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
ADSA: Sorting/ Advanced Data Structures and Algorithms Objective –examine popular sorting algorithms, with an emphasis on divide and conquer.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 7 Sorting.
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.
@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 22 Recursive Sorting, Heapsort & STL Quicksort Instructor: Zhigang Zhu Department.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
1 Sorting. 2 Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort a list,
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
Functional Design and Programming Lecture 4: Sorting.
Nov 21, Fall 2006IAT 8001 Binary Search Sorting. Nov 21, Fall 2006IAT 8002 Search  Often want to search for an item in a list  In an unsorted list,
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Recursion CITS1001.
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.
(c) , University of Washington
Recursion1. 2 What kind of problem is “recursive”? same Recursive problems are those problems where in order to solve the original problem you have to.
Building Java Programs Chapter 13 Searching reading: 13.3.
Copyright © 2007 Pearson Addison-Wesley. All rights reserved. A. Levitin “ Introduction to the Design & Analysis of Algorithms, ” 2 nd ed., Ch. 1 Chapter.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
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.
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
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 Searching & Sorting. Objective/Essential Standard Essential Standard 3.00 Apply Advanced Properties of Arrays Indicator 3.03 Apply procedures.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Introduction to Introduction to Programming with Data.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2.Solve smaller instances.
1 CSC212 Data Structure - Section AB Lecture 22 Recursive Sorting, Heapsort & STL Quicksort Instructor: Edgardo Molina Department of Computer Science City.
Merge Sort. Stable vs. Non-Stable Sorts We frequently use sorting methods for items with multiple keys Sometimes we need to apply the sorting with different.
Divide and Conquer Strategy
 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.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 4 Introduction.
Concepts of Algorithms CSC-244 Unit 15 & 16 Divide-and-conquer Algorithms ( Binary Search and Merge Sort ) Shahid Iqbal Lone Computer College Qassim University.
Sorting divide and conquer. Divide-and-conquer  a recursive design technique  solve small problem directly  divide large problem into two subproblems,
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Lecture # 6 1 Advance Analysis of Algorithms. Divide-and-Conquer Divide the problem into a number of subproblems Similar sub-problems of smaller size.
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
FASTER SORT using RECURSION : MERGE SORT COMP 103.
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Lecture 25: Searching and Sorting
Introduction to Algorithms: Divide-n-Conquer Algorithms
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
COMP 53 – Week Seven Big O Sorting.
Chapter 4 Divide-and-Conquer
Divide-and-Conquer The most-well known algorithm design strategy:
CS 3343: Analysis of Algorithms
CSC215 Lecture Algorithms.
Hassan Khosravi / Geoffrey Tien
Selection Insertion and Merge
Divide-and-Conquer The most-well known algorithm design strategy:
Algorithms: Design and Analysis
Sorting and Searching -- Introduction
CMPT 225 Lecture 10 – Merge Sort.
Presentation transcript:

Contest Algorithms January 2016 Pseudo-code for divide and conquer, and three examples (binary exponentiation, binary search, and mergesort). 5. Divide & Conquer 1Contest Algorithms: 5. Divide & Conquer

1. Divide-and-Conquer 1. Divide problem into two or more smaller instances 2.Solve smaller instances recursively ( conquer ) 3.Obtain solution to original (larger) problem by combining these solutions

Divide-and-Conquer Technique solve subproblem 2 of size n /2 a solution to subproblem 1 a solution to the original problem solve a problem of size n a recursive algorithm combine solutions solve subproblem 1 of size n /2 divide problem into smaller parts (often 2) a solution to subproblem 2

Divide-and-Conquer Examples  Binary exponentiation  Binary search  Sorting: mergesort and quicksort  (see QuickSort.java)  Closest Pair of Points Problem  see the Computational Geometry slides

5 2. Binary Exponentiation : x n public static long pow(long x, long n) { if (n <= 0) // n must be positive return 1; else if (n % 2 == 1) { // odd long p = pow(x, (n-1)/2); // pow of x faster than x 2 return x * p * p; } else { // n even long p = pow(x, n/2); return p * p; } } // end of pow() see Power.java

 Java interprets all numeral literals as 32-bit integers.  e.g. long x = ; // will give "integer number too large" error  int range: to ( )  If you want to write something bigger than a 32-bit integer, use the suffix L:  e.g. long x = L ; // accepted Writing long numbers Contest Algorithms: 4. Backtracking6

public static void main (String[] args) { System.out.println("5^2 = " + pow(5,2)); System.out.println("2^10 = " + pow(2,10)); for (int i=10; i <= 100; i=i+5) System.out.println("2^" + i + " = " + pow(2,i)); } // end of main() Using pow() Contest Algorithms: 4. Backtracking7

 Problems with overflow:  Three ways to solve it  write youe own multiply()  use Math.multiplyExact() in Java 8  use BigInteger  see "Maths" slides  BigInteger.pow(int exponent) Contest Algorithms: 4. Backtracking8

public static long mult(long a, long b) { if ((a != 0) && (b > Long.MAX_VALUE / a)) // detect overflow System.out.println("Overflow for a*b:\n " + a + " * " + b); return a*b; }  In pow(), replace the three uses of "*":  return mult(x, mult(p, p)); // was x * p * p  return mult(p, p); // was p * p Your own multiply() Contest Algorithms: 4. Backtracking9

10

 In pow(), replace the three uses of "*":  return Math.multiplyExact(x, Math.multiplyExact(p,p)); // was x * p * p  return Math.multiplyExact(p, p); // was p * p Use Math.multiplyExact() Contest Algorithms: 4. Backtracking11

Contest Algorithms: 4. Backtracking12

 addExact(), subtractExact(), multiplyExact()  incrementExact(), decrementExact()  toIntExact()  used when casting a long to an int  Instead of silently giving the wrong answer, they will throw a java.lang.ArithmeticException for overflows involving int or long calculations Java 8 "Exact" Math methods Contest Algorithms: 4. Backtracking13

 Binary Search is a divide and conquer algorithm.  Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Easy; return index 3. Binary Search Example: Find As implemented in Java by Arrays. binarySearch()

Example Example: Find Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Trivial.

Example: Find Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Trivial.

Example: Find Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Trivial.

Example: Find Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Trivial.

Find an element in a sorted array: 1.Divide: Check middle element. 2.Conquer: Recursively search 1 subarray. 3.Combine: Trivial. Example: Find

Binary Search Code private static int binarySearch(int[] arr, int val) { return binSrch(arr, val, 0, arr.length-1); } private static int binSrch(int[] arr, int val, int start, int end) { if (start > end) // val not found return -1; int middle = (start + end)/2; int midVal = arr[middle]; if (val == midVal) return middle; else if (val > midVal) // search right half return binSrch(arr, val, middle+1, end); else // search left half return binSrch(arr, val, start, middle-1); } // end of binSrch() see BinarySearchTest.java

public static void main (String[] args) { Integer[] intArr = {2, 3, 5, 7, 9, 10, 13, 15, 17, 19}; System.out.println("Index pos of 10: " + Arrays.binarySearch(intArr, 10)); System.out.println("Index pos of 22: " + Arrays.binarySearch(intArr, 22)); int[] arr = {2, 3, 5, 7, 9, 10, 13, 15, 17, 19}; System.out.println("Index pos of 10: " + binarySearch(arr, 10)); System.out.println("Index pos of 22: " + binarySearch(arr, 22)); } // end of main() Using Both Functions Contest Algorithms: 4. Backtracking21 Index pos of 10: 5 Index pos of 22: -11 Index pos of 10: 5 Index pos of 22: -1

22 4. Mergesort  A stable sorting algorithm with worst-case running time O(n log n)  Algorithm:  Divide the list into two sub-lists  Sort each sub-list (recursion)  Merge the two sorted sub-lists

23 Code public static void mergeSort(int[] arr) { int[] temp = new int[arr.length]; msort(arr, temp, 0, arr.length); } private static void msort(int[] arr, int[] temp, int left, int right) { // continue only if the sub-array has more than 1 element if ((left + 1) < right) { int mid = (right + left)/2; msort(arr, temp, left, mid); msort(arr, temp, mid, right); merge(arr, temp, left, mid, right); } } // end of msort() O(n) see MergeSort.java

merge Tracing msort()

Merging two sorted arrays The merge() function

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays

Merging two sorted arrays Time = one pass through each array =  (n) to merge a total of n elements (linear time).

private static void merge(int[] arr, int[] temp, int left, int mid, int right) { // are the two sub-arrays already in sorted order? if (arr[mid-1] <= arr[mid]) return; int indexA = left; // to scan 1st sub-array int indexB = mid; // to scan 2nd sub-array int i = left; // for moving over temp array // compare arr[indexA] and arr[indexB]; copy the smaller to temp while ((indexA < mid) && (indexB < right)) { if (arr[indexA] < arr[indexB]) temp[i++] = arr[indexA++]; // copy and move idxs else temp[i++] = arr[indexB++]; } :

: // copy the tail of the sub-array that is not finished while (indexA < mid) temp[i++] = arr[indexA++]; while (indexB < right) temp[i++] = arr[indexB++]; // copy from temp back to arr for (int j = left; j < right; j++) arr[j] = temp[j]; } // end of merge() Contest Algorithms: 4. Backtracking39

public static void main (String[] args) { int[] arr = {18, 3, 5, 23, 4, 17, 2, 16, 19}; System.out.println("Unsorted array: " + Arrays.toString(arr)); mergeSort(arr); System.out.println("Sorted array: " + Arrays.toString(arr)); Integer[] intArr = {18, 3, 5, 23, 4, 17, 2, 16, 19}; Arrays.sort(intArr); // quicksort System.out.println("Sorted array: " + Arrays.toString(intArr)); } // end of main() Using Two Sorts Contest Algorithms: 4. Backtracking40

Contest Algorithms: 4. Backtracking41