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
?
W ll
h
t d
b
b tt
?
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 object
For a conditional, count
number of basic steps on the
branch that is executed
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
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '07
 FRANCIS
 Algorithms, Analysis of algorithms, Computational complexity theory, int item, basic steps, worstcase time

Click to edit the document details