12 Searching and Asymptotic Complexity

12 Searching and Asymptotic Complexity - 9/30/2010 What...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
9/30/2010 1 SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY Lecture 12 CS2110 – Fall 2009 What Makes a Good Algorithm? 2 ± Suppose you have two possible algorithms or data structures that basically do the same thing; which is better ? Wl l ht d b bt t ± Well… what do we mean by better ? ± Faster? ± Less space? ± Easier to code? ± Easier to maintain? ± Required for homework? ± How do we measure time and space for an algorithm? Sample Problem: Searching 3 ± static boolean find(int[] a, int item) { ± for (int i = 0; i < a.length; i++) { ± if (a[i] == item) return true; Determine if a sorted array of integers contains a given integer First solution: Linear Search (check each element) ± } ± return false; ± } static boolean find(int[] a, int item) { for ( int x : a ) { if (x == item) return true; } return false; } Sample Problem: Searching 4 static boolean find (int[] a, int item) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high)/2; Second solution: Binary Search if (a[mid] < item) low = mid + 1; else if (a[mid] > item) high = mid - 1; else return true; } return false; } Linear Search vs Binary Search 5 ± Which one is better? ± Linear Search is easier to program ± But Binary Search is faster… isn’t it? Simplifying assumption #1: Use the size of the input rather than the input itself ± How do we measure to show that one is faster than the other ± Experiment? ± Proof? ± Which inputs do we use? ² For our sample search problem, the input size is n+1 where n is the array size Simplifying assumption #2: Count the number of “ basic steps ” rather than computing exact times One Basic Step = One Time Unit 6 ± Basic step: ± input or output of a scalar value ± accessing the value of a scalar variable, array element, or field of an objec For a conditional, count number of basic steps on the branch that is executed an object ± assignment to a variable, array element, or field of an object ± a single arithmetic or logical operation ± method invocation (not counting argument evaluation and execution of the method body) For a loop, count number of
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/30/2011 for the course CS 2110 taught by Professor Francis during the Fall '07 term at Cornell University (Engineering School).

Page1 / 5

12 Searching and Asymptotic Complexity - 9/30/2010 What...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online