03 Analysis Sort
03 Analysis Sort
Algorithms
Lesson 03:
Runtime Analysis and Sorting
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i];
}
return sum;
}
•
Scalability
• When analyzing algorithms, we will not look at the low level
optimization details
• 18,446,744,073,709,551,615
• ie, 18 Quintillions
Analysis of Algorithms
•
Which Is Better?
•
Large N???
• How do we define large?
• 10? 50? 10000000000000000???
Doom (2016)
Doom (1993)
Scalability
•
Big O Upper Bound
•
• g(n) = n
• Examples: c = 2, n’ = 1
• Examples: c = 11, n’ = 1
• Examples: c = 12, n’ = 3
• Examples: c = 1, n’ = 6
• Examples: c = 1, n’ = 1
• Examples: c = 7, n’ = 1
•
Big O Rules of Thumb
•
Notation
•
Big Ω Lower Bound
•
•
public static int sum(int[] array){
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i];
}
return sum;
}
•
Purple represents possible actual runtimes for those bounds
1 log n n n log n n2 n3 2n
In Practice
•
A Big Mistake
•
public static void doSomething(int[] array){
•
Let’s Dig Into the Math…
public static void doSomething(int[] array){
•
•
Sorting
Consider a Playlist
Sort by Title or Artist,
Ascending or Descending
How do you sort when
playing cards?
Sorting Algorithms
• Many different sorting algorithms, with different properties
• Given two items A and B, just need a comparator that can state which
one is greater or equal
• easy to say that 5 greater than 2, but what does it mean that song A is greater than
song B? e.g., could look at alphabetic ordering of titles or artist names
• Tractable mathematically
• So good example to show how to analyze algorithms
Sorting Algorithms
• Bubble Sort
• Insertion Sort
• There are more, but those are the most famous that you
need to know
Swap
•
Insertion Sort
• An array of size 0 or 1 is 4 5 1 3 2 6 K=0
always considered sorted
4 5 1 3 2 6 K=1
• From left to right, till length N
4 5 1 3 2 6 K=2
• K-leftmost values are sorted
4 5 1 3 2 6 K=3
• Position K+1 is not sorted,
4 1 5 3 2 6 swap
insert it in the first K
• by swapping adjacent elements, like
1 4 5 3 2 6 swap
in Bubble Sort
Cont.
1 4 5 3 2 6 K=4
1 4 3 5 2 6 swap
1 3 4 5 2 6 swap
1 3 4 5 2 6 K=5
1 3 4 2 5 6 swap
1 3 2 4 5 6 swap
1 2 3 4 5 6 swap
1 2 3 4 5 6 K=6
Best vs. Worst Case
•
Homework