Docsity

Recursion, Mergesort, and Quicksort Algorithms in Java, Slides of Design

Partial preview of the text

Download Recursion, Mergesort, and Quicksort Algorithms in Java and more Slides Design in PDF only on Docsity!

cs2420 | Introduction to Algorithms and Data Structures | Spring 2015

MERGESORT & QUICKSORT

administrivia…

last time…

re ⋅ cur ⋅ sion

[ri- kur -zh uh n]
noun

see recursion.

a simple example

sum(N) = sum(N-1) + N public static int sum(int n) { if(n == 1) return 1; return sum(n-1) + n; } how can we solve the same problem without recursion? which is better, the recursive solution or the alternative? fix to handle zero or negative values...

  • recursive methods often have unusual parameters
    • at the top level, we just want:
    • but in reality, we have to call:
  • driver methods are wrappers for calling recursive
methods
  • driver makes the initial call to the recursive method,
knowing what parameters to use
  • is not recursive itself binarySearch(arr, item); binarySearch(arr, item, 0, arr.length-1); public static boolean binarySearch(arr, item){ return binarySearchRecursive( arr, item, 0, arr.length-1); }

4 recursion rules

  1. always have at least one case that can be solved without using recursion
  2. any recursive call must progress toward a base case
  3. always assume that the recursive call works, and use this assumption to design your algorithms
  4. never duplicate work by solving the same instance of a problem in separate recursive calls

today…

mergesort

divide and conquer

but first, merging…

  • say we have two sorted lists, how can we efficiently merge them?
  • idea: compare the first element in each list to each other, take the smallest and add to the merged list - AND… repeat

what does this look like?

mergesort

1)divide the array in half 2)sort the left half 3)sort the right half 4)merge the two halves together

what does this look like?

  1. take the left half, and go back to step 1
  2. take the right half, and go back to step 1 until??? until???

void mergesort(int[] arr, int left, int right) { int mid = (left + right) / 2; mergsort(arr, left, mid); mergsort(arr, mid+1, right); merge(arr, left, mid+1, right); } divide conquer

what are we missing?

void mergesort(int[] arr, int left, int right) { // arrays of size 1 are already sorted if(start >= end) return; int mid = (left + right) / 2; mergsort(arr, left, mid); mergsort(arr, mid+1, right); merge(arr, left, mid+1, right); } 19 divide conquer what is the complexity of the conquer step? A) c B) log N C) N D) N log N E) N 2 F) N 3

void mergesort(int[] arr, int left, int right) { // arrays of size 1 are already sorted if(start >= end) return; int mid = (left + right) / 2; mergsort(arr, left, mid); mergsort(arr, mid+1, right); merge(arr, left, mid+1, right); } 20 divide conquer what is the complexity of MERGESORT? A) c B) log N C) N D) N log N E) N 2 F) N 3 is this the worst || average || best-case?