Lecture10 Handouts Proto
Lecture10 Handouts Proto
Lecture #10
• Big-O aka “How Fast Is that Algorithm?”
• Sorting Algorithms, part I
• Appendix - ShellSort
Big-O
2
AT USC
Big-O
What’s the big picture?
Big-O is a technique that lets you quickly
understand an algorithm’s efficiency.
A
B
N numbers.”
“I’m trying to sort 1000
“Algorithm A takes 5 5·N 2
million instructions to do that.”
“Algorithm B takes 307 million instructions to do that.”
37,000·N
So we’d say:
“The Big-O of Algorithm X is N2.”
Big-O
So how do we compute the Big-O of a function?
Big-O Simplification
Actually, if you think about it, there’s no need to compute
the exact f(n) of an algorithm…
int arr[n][n];
for ( int i = 0; i < n; i++ ) f(n) = n2
for ( int j = 0; j < n; j++ ) Our algorithm is O(n2).
arr[i][j] = 0;
17
Big-O
So if I say: “This algorithm is O(n2).”
I really mean: “To process n items, this algorithm requires
roughly n2 operations.”
significant term
3500
3000
(e.g. n2 from 2n2+3n+1) Number of operations
2500
1000
Big-O Complexity
log2n N nlog2n n2 n3 2n
Big-O Complexity
1,000,000,000,000,000,000 vs 19,000,000!
Say you improve an O(n3) algorithm from f(n) = 5n3 steps to f(n) = 1.5n3
steps. For n=1,000,000, that reduces the number of steps from
5,000,000,000,000,000,000 to 1,500,000,000,000,000,000.
(Big deal… so it’ll take 1.5 years to run instead of 5 years)
2500
lots of headaches.
21
2500
lots of headaches.
Find the Big-O Challenge, Part 1
22
{ sum += i;
O(N*log3N)
sum++;
O(log2N)
O(N3)
}
bottom, left to
From top to
Find the Big-O Challenge, Part 1a
23
arr[n] = addMe;
matter how large
of steps, no
n = n + 1;
constant number
one step or a
}
O(1) or O(C) – just
O(N)
bottom:
From top to
Big-O… my
24
void mystery(int n)
{
for ( int q = 0; q < n; q++ )
Sometimes you’ll run into an algorithm {
that isn’t so clear-cut. For example, for (int x = 0 ; x < q ; x++)
what’s the Big-O of mystery? {
cout << “Waahoo!”;
}
It’s clear that the outer loop runs n }
times, but what about the inner loop? }
sum++;
O(Q4)
O(N2)
left to right:
From top to bottom,
27
for (int i=0 ; i < n ; i++) for (int i=0 ; i < n ; i++)
{
cout << “Muahahaha!”; if (i == n/2)
{
for (int i=0 ; i < q*q ; i++) for ( int k = 0; k < q; k++ ) on all of the N items!
And as such,
Ok, our vector our loop runs
contains q values… q times… And each time our loop
runs, we:
void printNums( vector<int> & v ) 1. Access an item: the
{ cost of accessing an item
int q = v.size(); in a vector is O(1) - so
for ( int i = 0; i < q ; i++ ) we’ll remember that!
{
int a = v[0]; // get 1st item 2. Erase the first item in the
vector: the Big-O of erasing the
cout << a; // print it out
first item in a vector with q items
v.erase( v.begin() ); // erase 1st is O(q).
item
v.push_back(a); // add it to 3. Add the item to the end of the
end vector: the Big-O of adding an item
}
to the end of a vector is O(1).
} Hint:
The STL vector
Total steps performed during our loop:
Insert at the top/middle: O(n)
q * (1 + q + 1 ) Insert an the end: O(1)
Delete an item from top/middle: O(n)
So our total Big-O is: Delete an item from the end: O(1)
Access an item: O(1)
O(q2)
Finding an item: O(n)
33
Hints:
The STL vector During eachTheiteration,
STL set we delete
Insert at the top/middle: O(n) the
Inserting vector’s
a new item: last item.
O(log2n)
Insert an the end: O(1) Finding an item: O(log2n)
Delete an item from top/middle: O(n) Let’s assume
Deleting the vector always
an item: O(loghas
2n)
z
Delete an item from the end: O(1) items, no matter what.
Access an item: O(1)
Finding an item: O(n) Cost of deleting last item: O(1)
Find the Big-O Challenge, Part 5
38
Q
{1,9,…} I have a vector of sets of ints:
{2,3,…}
vector< set<int> > v;
{-7, 8,…}
N You may assume vector v has N total sets in it.
{4,5,8,…}
You may assume that each set has an avg of Q items.
{}
{-1,0,1,…} Questions:
#1 What is the Big-O of determining if the first set, v[0],
contains the value 7?
#2 What is the Big-O of determining if any set in v has a value of 7?
#4 What is the Big-O of finding the first set with a value of 7 and then counting
the number of even values in that set?
Constraints?
• Are the items in RAM or on disk?
• Is the data in an array or a linked list?
Carey’s 2 Rules
44
of Sorting
Rule #1:
Don’t choose a sorting algorithm until you
understand the requirements of your problem.
Rule #2:
Always choose the simplest sorting algorithm
possible that meets your requirements.
45
}
int minIndex = i;
for (int j = i+1; j < n; j++) Locate the smallest item
{
if (A[j] < A[minIndex]) -
in the array between the
ith slot and slot n-1.
minIndex = j;
}
}
swap(A[i], A[minIndex]); }-
Swap the smallest item
found with slot A[i].
}
What’s a Stable Sort?
49
And the drugstore wants to sort them and serve them based on urgency.
…
+ 2 steps in round 2
shift up to two books to find the right spot.
+…
+ N-1 steps in last rnd
During the last round, we may need to = roughly N2 steps
shift up to N-1 books to find the right spot.
Any ideas?
When you hit the end of the array, if you made at least one swap on your
way down, then start back at the top and repeat the whole process again!
60
?
SWAP? some of the hottest peppers…
…to sort them from least
spicy to most spicy!
do Start by assuming
that we won’t
{
do any swaps
atLeastOneSwap = false;
for (int j = 0; j < (n-1); j++)
{ Compare each element
if (Arr[j] > Arr[j + 1]) with its neighbor and
{ swap them if they’re
Swap(Arr[j],Arr[j+1]); out-of-order.
atLeastOneSwap = true;
Don’t forget-we swapped!
}
}
} If we swapped at least
while (atLeastOneSwap == true); once, then start back at
} the top and repeat the
whole process.
63
selectionSort
Sorting Challenge For each of the N books
Find the smallest book between
slots i and N
Consider the following array
Swap this smallest book with
of integers: book i
By one round, I
mean one full trip insertionSort
through the sort’s 2 5 9 14 7 3 s=2
while/for loop. While books need sorting:
Focus on the first s books
If the last book in set is in the
which has been sorted by wrong order THEN
one round of either selection A. Remove it from shelf
sort, insertion sort or bubble B. Shift the books to
sort. the right as required
C. Insert our book into the
proper slot
Which of these sorts could NOT s=s+1
have been used on this array? bubbleSort
Why? while the shelf isn’t sorted
repeatedly swap adjacent books
if they’re out of order
64
Appendix
Pick a value of h
For each element in the array:
• If A[i] and A[i+h] are out of order then
• Swap the two elements
If you swapped any elements during the last pass,
then repeat the entire process again (same h value).
66
SWAP?
67
SWAP?
68
The Shellsort:
This time we had no swaps! h-sorting
Our of
Pick a value array
h is now 3-sorted!
For each element in the array: Let’s 3-sort this array so
This means that every element
the shells are ascending.
• If A[i] and A[i+h] are
is smaller thanout of order
e.g., h=3
• Swap the two
the element elements
3 items later
If you swappedinany theelements,
array.
repeat the entire it’s
Of course, process again.
not completely Question:
sorted
i yet, just 3-sorted!
i+3 If you 1-sort an array,
which other sort
algorithm does this
remind you of?
SWAP?
69
Step 2:
First completely 8-sort the array…
Then completely 4-sort the array…
Then completely 2-sort the array…
Finally, completely bubble
1-sortsort the array…
and the array’s now fully sorted!
The Shellsort
Let’s do an example on the board:
9 5 2 14 3 7
72
selectionSort
Sorting Challenge For each of the N books
Find the smallest book between
slots i and N
Given the following numbers, Swap this smallest book with
book i
show what they would look
like after one, two and three insertionSort
outer-loop iterations of s=2
While books need sorting:
selection sort, insertion sort Focus on the first s books
and bubble sort: If the last book in set is in the
wrong order THEN
A. Remove it from shelf
9 5 2 14 3 7 B. Shift the books to
the right as required
C. Insert our book into the
proper slot
s=s+1
bubbleSort
while the shelf isn’t sorted
repeatedly swap adjacent books
if they’re out of order