SlideShare a Scribd company logo
1 of 111
Download to read offline
Data Structures
Introduction
Andres Mendez-Vazquez
May 16, 2015
1 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
2 / 50
Images/ITESM.p
Introduction
Data Manipulation
Data structures is concerned with the representation and manipulation of
data.
Further
All programs manipulate data.
Thus!!!
So, all programs represent data in some way.
Data manipulation requires a data structure and an algorithm!!!
3 / 50
Images/ITESM.p
Introduction
Data Manipulation
Data structures is concerned with the representation and manipulation of
data.
Further
All programs manipulate data.
Thus!!!
So, all programs represent data in some way.
Data manipulation requires a data structure and an algorithm!!!
3 / 50
Images/ITESM.p
Introduction
Data Manipulation
Data structures is concerned with the representation and manipulation of
data.
Further
All programs manipulate data.
Thus!!!
So, all programs represent data in some way.
Data manipulation requires a data structure and an algorithm!!!
3 / 50
Images/ITESM.p
Introduction
Data Manipulation
Data structures is concerned with the representation and manipulation of
data.
Further
All programs manipulate data.
Thus!!!
So, all programs represent data in some way.
Data manipulation requires a data structure and an algorithm!!!
3 / 50
Images/ITESM.p
Examples
Data Bases
Using B-trees for fast access to the records!!!
4 / 50
Images/ITESM.p
Example
Storing Sparse Matrices
5x5 Matrix
Numeric Elements
Empty Elements
Sparse Matrix
Why?
Reduce the amount memory used for storage!!!
5 / 50
Images/ITESM.p
Example
Storing Sparse Matrices
5x5 Matrix
Numeric Elements
Empty Elements
Sparse Matrix
Why?
Reduce the amount memory used for storage!!!
5 / 50
Images/ITESM.p
Example
Shortest Path in a Map
6 / 50
Images/ITESM.p
What is the course about?
First
Understanding Data Structure and Algorithms needed to develop programs
for data manipulation.
Why?
The study of Data Structures and Algorithms is fundamental to Computer
Science.
7 / 50
Images/ITESM.p
What is the course about?
First
Understanding Data Structure and Algorithms needed to develop programs
for data manipulation.
Why?
The study of Data Structures and Algorithms is fundamental to Computer
Science.
7 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
8 / 50
Images/ITESM.p
In sorting, we want to have the following
Rearrange a sequence of numbers
9,3,4,2,1
Into an increasing sequence
1, 2, 3, 4, 9
Or Into a decreasing sequence
9, 4, 3, 2, 1
9 / 50
Images/ITESM.p
In sorting, we want to have the following
Rearrange a sequence of numbers
9,3,4,2,1
Into an increasing sequence
1, 2, 3, 4, 9
Or Into a decreasing sequence
9, 4, 3, 2, 1
9 / 50
Images/ITESM.p
In sorting, we want to have the following
Rearrange a sequence of numbers
9,3,4,2,1
Into an increasing sequence
1, 2, 3, 4, 9
Or Into a decreasing sequence
9, 4, 3, 2, 1
9 / 50
Images/ITESM.p
Notation
For now, we will assume that the data
It is an array A.
Meaning
item 9 3 4 2 1
index 0 1 2 3 4
Thus
If we need to reference elements on the array through an index, we use
the following notation
A [index] (1)
10 / 50
Images/ITESM.p
Notation
For now, we will assume that the data
It is an array A.
Meaning
item 9 3 4 2 1
index 0 1 2 3 4
Thus
If we need to reference elements on the array through an index, we use
the following notation
A [index] (1)
10 / 50
Images/ITESM.p
Notation
For now, we will assume that the data
It is an array A.
Meaning
item 9 3 4 2 1
index 0 1 2 3 4
Thus
If we need to reference elements on the array through an index, we use
the following notation
A [index] (1)
10 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
11 / 50
Images/ITESM.p
Naive Algorithm
What if we do the following
1 Pick an element in the array A.
2 Put that element in the correct position.
Thus
We will concentrate first in inserting the element in the correct position
For this imagine the following
We already have an array A = [1|3|6|4| − |−] where “-” represents null
elements.
12 / 50
Images/ITESM.p
Naive Algorithm
What if we do the following
1 Pick an element in the array A.
2 Put that element in the correct position.
Thus
We will concentrate first in inserting the element in the correct position
For this imagine the following
We already have an array A = [1|3|6|4| − |−] where “-” represents null
elements.
12 / 50
Images/ITESM.p
Naive Algorithm
What if we do the following
1 Pick an element in the array A.
2 Put that element in the correct position.
Thus
We will concentrate first in inserting the element in the correct position
For this imagine the following
We already have an array A = [1|3|6|4| − |−] where “-” represents null
elements.
12 / 50
Images/ITESM.p
Naive Algorithm
What if we do the following
1 Pick an element in the array A.
2 Put that element in the correct position.
Thus
We will concentrate first in inserting the element in the correct position
For this imagine the following
We already have an array A = [1|3|6|4| − |−] where “-” represents null
elements.
12 / 50
Images/ITESM.p
Thus
Where do we start comparing to insert?
Ideas?
Maybe
Let us do it with
A = [1|3|6|4| − |−]
13 / 50
Images/ITESM.p
Thus
Where do we start comparing to insert?
Ideas?
Maybe
From the right!!! After all we have space
Let us do it with
A = [1|3|6|4| − |−]
13 / 50
Images/ITESM.p
Thus
Where do we start comparing to insert?
Ideas?
Maybe
From the right!!! After all we have space
Let us do it with
A = [1|3|6|4| − |−]
13 / 50
Images/ITESM.p
What about the code?
What do we use for going through a sequence?
Ideas?
In addition, we need to make space
For the new item.
Code
14 / 50
Images/ITESM.p
What about the code?
What do we use for going through a sequence?
Ideas?
In addition, we need to make space
For the new item.
Code
14 / 50
Images/ITESM.p
What about the code?
What do we use for going through a sequence?
Ideas?
In addition, we need to make space
For the new item.
Code
p r i v a t e i n t [ ] i n s e r t ( i n t [ ] A, i n t t ){
// Extra V a r i a b l e s
i n t j ;
// I n s e r t i n t o A [ 0 : i −1]
f o r ( j = A. lenght −1; j >=0 && t<A[ j ] ; j −−){
// s h i f t to the r i g h t
A[ j +1]=A[ j ] ; }
A[ j +1]=t ;
r e t u r n A;
}
14 / 50
Images/ITESM.p
Ok, We have that...Now what?
How do we use this piece of code for the insertion sort?
Ideas?
Problem with the code!!
You require that the array where you insert to be sorted!!!
Look at this!!! At the Board...
Thus
How do we solve this problem?
15 / 50
Images/ITESM.p
Ok, We have that...Now what?
How do we use this piece of code for the insertion sort?
Ideas?
Problem with the code!!
You require that the array where you insert to be sorted!!!
Look at this!!! At the Board...
Thus
How do we solve this problem?
15 / 50
Images/ITESM.p
Ok, We have that...Now what?
How do we use this piece of code for the insertion sort?
Ideas?
Problem with the code!!
You require that the array where you insert to be sorted!!!
Look at this!!! At the Board...
Thus
How do we solve this problem?
15 / 50
Images/ITESM.p
Then, Insertion Sort works like this
First
Start with a sequence of size 1.
After all an array with one element is sorted!!!
Second
Repeatedly insert remaining elements
Example
Sort 7, 3, 5, 6, 1
16 / 50
Images/ITESM.p
Then, Insertion Sort works like this
First
Start with a sequence of size 1.
After all an array with one element is sorted!!!
Second
Repeatedly insert remaining elements
Example
Sort 7, 3, 5, 6, 1
16 / 50
Images/ITESM.p
Then, Insertion Sort works like this
First
Start with a sequence of size 1.
After all an array with one element is sorted!!!
Second
Repeatedly insert remaining elements
Example
Sort 7, 3, 5, 6, 1
16 / 50
Images/ITESM.p
Final Code
Something Notable
// Sort A assume i s f u l l
p u b l i c i n t [ ] I n s e r t i o n S o r t ( i n t [ ] A){
// Extra Space
i n t B [ ] = new i n t [A. l e n g t h ] ;
// I n i t Array B
B[0]=A [ 0 ] ;
i n t s i z e = 1;
i n t j , t ;
f o r ( i n t i = 1; i < A. l e n g t h ; i ++){
t = A[ i ] ;
f o r ( j = s i z e −1; j >=0 && t<B[ j ] ; j −−)
{
// s h i f t to the r i g h t
B[ j +1]=B[ j ] ; }
B[ j +1]=t ;
s i z e ++;
}
r e t u r n B;
}
17 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
18 / 50
Images/ITESM.p
Question: Which Complexity You Have with Insertion
Sort?
After all you have!!!
Time Complexity!!!
For this, we have
Time Complexity Techniques:
Count a particular operation
Count number of steps
Asymptotic complexity
19 / 50
Images/ITESM.p
Question: Which Complexity You Have with Insertion
Sort?
After all you have!!!
Time Complexity!!!
For this, we have
Time Complexity Techniques:
Count a particular operation
Count number of steps
Asymptotic complexity
19 / 50
Images/ITESM.p
Question: Which Complexity You Have with Insertion
Sort?
After all you have!!!
Time Complexity!!!
For this, we have
Time Complexity Techniques:
Count a particular operation
Count number of steps
Asymptotic complexity
19 / 50
Images/ITESM.p
Question: Which Complexity You Have with Insertion
Sort?
After all you have!!!
Time Complexity!!!
For this, we have
Time Complexity Techniques:
Count a particular operation
Count number of steps
Asymptotic complexity
19 / 50
Images/ITESM.p
Question: Which Complexity You Have with Insertion
Sort?
After all you have!!!
Time Complexity!!!
For this, we have
Time Complexity Techniques:
Count a particular operation
Count number of steps
Asymptotic complexity
19 / 50
Images/ITESM.p
Basically, we will use the second one
First Look at this part of the code
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Then
How many comparisons are made?
20 / 50
Images/ITESM.p
Basically, we will use the second one
First Look at this part of the code
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Then
How many comparisons are made?
20 / 50
Images/ITESM.p
The Possible Cases
Worst-case count
Maximum count
Best-case count
Minimum count
In addition, we have
Average Count
21 / 50
Images/ITESM.p
The Possible Cases
Worst-case count
Maximum count
Best-case count
Minimum count
In addition, we have
Average Count
21 / 50
Images/ITESM.p
The Possible Cases
Worst-case count
Maximum count
Best-case count
Minimum count
In addition, we have
Average Count
21 / 50
Images/ITESM.p
Example: Worst-Case For the Code
Code, Look at the red compares
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Case I
If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares.
What about the general case
If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares.
22 / 50
Images/ITESM.p
Example: Worst-Case For the Code
Code, Look at the red compares
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Case I
If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares.
What about the general case
If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares.
22 / 50
Images/ITESM.p
Example: Worst-Case For the Code
Code, Look at the red compares
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Case I
If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares.
What about the general case
If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares.
22 / 50
Images/ITESM.p
Worst-Case For An Almost Final Version
Simplified Version
Remember s i z e i s the s i z e of B
f o r ( i = 2; i < A. l e n g t h ; i++ )
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Worst Case for the Outer Loop
1 Outer loop takes n steps
What about the inner loop?
Answer
23 / 50
Images/ITESM.p
Worst-Case For An Almost Final Version
Simplified Version
Remember s i z e i s the s i z e of B
f o r ( i = 2; i < A. l e n g t h ; i++ )
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Worst Case for the Outer Loop
1 Outer loop takes n steps
What about the inner loop?
Answer
23 / 50
Images/ITESM.p
Worst-Case For An Almost Final Version
Simplified Version
Remember s i z e i s the s i z e of B
f o r ( i = 2; i < A. l e n g t h ; i++ )
f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−)
B[ j +1]=B[ j ] ;
Worst Case for the Outer Loop
1 Outer loop takes n steps
What about the inner loop?
Answer
Number of steps in the inner loop = size+1
23 / 50
Images/ITESM.p
What is the range of j?
Very Simple
For the first step j = 1 − 1 =⇒Number of Steps = 2
For the last step j = n − 1 − 1 =⇒Number of Steps = n
Total Compares
2 + 3 + 4 + ... + n =
n (n + 1)
2
− 1 (2)
24 / 50
Images/ITESM.p
What is the range of j?
Very Simple
For the first step j = 1 − 1 =⇒Number of Steps = 2
For the last step j = n − 1 − 1 =⇒Number of Steps = n
Total Compares
2 + 3 + 4 + ... + n =
n (n + 1)
2
− 1 (2)
24 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
25 / 50
Images/ITESM.p
A more realistic step count
Counting when A.length = n
// Sort A assume i s f u l l
p u b l i c i n t [ ] I n s e r t i o n S o r t ( i n t [ ] A){ Step
// I n i t i a l V a r i a b l e s 0
i n t B [ ] = new i n t [A. l e n g t h ] ; 1
i n t s i z e = 1; 1
i n t i , j , t ; 1
// I n i t i a l i z e the Array B 0
B[0]=A [ 0 ] ; 1
f o r ( i = 1; i < A. l e n g t h ; i ++){ n
t = A[ i ] ; n−1
f o r ( j=s i z e −1;
j>=0&&t<B[ j ] ; j −−) i +1
{
// s h i f t to the r i g h t 0
B[ j +1]=B[ j ] ; } i
B[ j +1]=t ; n−1
s i z e ++; n−1
}
r e t u r n B; 1
}
26 / 50
Images/ITESM.p
The Result
Step count for body of for loop is
6 + 3 (n − 1) + n +
n−1
i=1
(i + 1) +
n−1
j=1
(i) (3)
The summation
They have the quadratic terms n2.
Complexity
Insertion sort complexity is O n2
27 / 50
Images/ITESM.p
The Result
Step count for body of for loop is
6 + 3 (n − 1) + n +
n−1
i=1
(i + 1) +
n−1
j=1
(i) (3)
The summation
They have the quadratic terms n2.
Complexity
Insertion sort complexity is O n2
27 / 50
Images/ITESM.p
The Result
Step count for body of for loop is
6 + 3 (n − 1) + n +
n−1
i=1
(i + 1) +
n−1
j=1
(i) (3)
The summation
They have the quadratic terms n2.
Complexity
Insertion sort complexity is O n2
27 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
28 / 50
Images/ITESM.p
Definition of Big O
Definition
For a given function g(n)
O(g(n)) ={f (n)| There exists c > 0 and n0 > 0
s.t. 0 ≤ f (n) ≤ cg(n) ∀n ≥ n0}
Graphically
29 / 50
Images/ITESM.p
Definition of Big O
Definition
For a given function g(n)
O(g(n)) ={f (n)| There exists c > 0 and n0 > 0
s.t. 0 ≤ f (n) ≤ cg(n) ∀n ≥ n0}
Graphically
29 / 50
Images/ITESM.p
What?
The term n0
It tells you when for the following n s you will have that f (n) ≤ cg(n)
What about the so called c
It can be seen a way to “increase” or “decrease” the height of the
function!!!
30 / 50
Images/ITESM.p
What?
The term n0
It tells you when for the following n s you will have that f (n) ≤ cg(n)
What about the so called c
It can be seen a way to “increase” or “decrease” the height of the
function!!!
30 / 50
Images/ITESM.p
What?
The term n0
It tells you when for the following n s you will have that f (n) ≤ cg(n)
What about the so called c
It can be seen a way to “increase” or “decrease” the height of the
function!!!
30 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
31 / 50
Images/ITESM.p
What does this means for insertion sort?
We have
6 + 3 (n − 1) + n +
n−1
i=1
(i + 1) +
n−1
j=1
(i) = ...
3 + 4n +
n (n − 1)
2
+ n − 1 +
n (n − 1)
2
= ...
2 + 5n + n(n − 1) = ...
n2
+ 4n + 2 ≤ n2
+ 4n2
+ 2n2
Thus
n2
+ 4n + 2 ≤ 7n2
(4)
With Tinsertion(n) = n2 + 4n + 2 describing the number of steps for
insertion when we have n numbers.
32 / 50
Images/ITESM.p
What does this means for insertion sort?
We have
6 + 3 (n − 1) + n +
n−1
i=1
(i + 1) +
n−1
j=1
(i) = ...
3 + 4n +
n (n − 1)
2
+ n − 1 +
n (n − 1)
2
= ...
2 + 5n + n(n − 1) = ...
n2
+ 4n + 2 ≤ n2
+ 4n2
+ 2n2
Thus
n2
+ 4n + 2 ≤ 7n2
(4)
With Tinsertion(n) = n2 + 4n + 2 describing the number of steps for
insertion when we have n numbers.
32 / 50
Images/ITESM.p
Actually
For n0 = 2
22
+ 4 × 2 + 2 = 14 < 7 × 22
= 28 (5)
Graphically
33 / 50
Images/ITESM.p
Actually
For n0 = 2
22
+ 4 × 2 + 2 = 14 < 7 × 22
= 28 (5)
Graphically
33 / 50
Images/ITESM.p
Meaning
First
Time or number of operations does not exceed cn2 for a constant c on
any input of size n (n suitably large).
Questions
Is O(n2) too much time?
Is the algorithm practical?
For this imagine, we have a machine able to make
109instructions/seconds
34 / 50
Images/ITESM.p
Meaning
First
Time or number of operations does not exceed cn2 for a constant c on
any input of size n (n suitably large).
Questions
Is O(n2) too much time?
Is the algorithm practical?
For this imagine, we have a machine able to make
109instructions/seconds
34 / 50
Images/ITESM.p
Meaning
First
Time or number of operations does not exceed cn2 for a constant c on
any input of size n (n suitably large).
Questions
Is O(n2) too much time?
Is the algorithm practical?
For this imagine, we have a machine able to make
109instructions/seconds
34 / 50
Images/ITESM.p
Meaning
First
Time or number of operations does not exceed cn2 for a constant c on
any input of size n (n suitably large).
Questions
Is O(n2) too much time?
Is the algorithm practical?
For this imagine, we have a machine able to make
109instructions/seconds
34 / 50
Images/ITESM.p
Then
We have the following
n n n log n n2
n3
n4
1000 1 micros 10 micros 1 milis 1 second 17 minutes
10,000 10 micros 130 micros 100 milis 17 minutes 116 days
106
1 milis 20 milis 17 minutes 32 years 3 × 107
years
It is much worse
35 / 50
Images/ITESM.p
Then
We have the following
n n n log n n2
n3
n4
1000 1 micros 10 micros 1 milis 1 second 17 minutes
10,000 10 micros 130 micros 100 milis 17 minutes 116 days
106
1 milis 20 milis 17 minutes 32 years 3 × 107
years
It is much worse
n n10
2n
1000 3.2 × 1013 years 3.2 × 10283 years
10,000 ??? ???
106
????? ?????
The Reign of the Non Polynomial Algorithms
35 / 50
Images/ITESM.p
Basically
These complexities allow us to compare algorithms
You can compare 2 algorithms having different asymptotic complexity
For example two types of sorting algorithms with O(n) and O(n2)
complexities.
However
This notation does not account for constant factors.
For example
For many cases of n, 1010n is much worse than n2.
36 / 50
Images/ITESM.p
Basically
These complexities allow us to compare algorithms
You can compare 2 algorithms having different asymptotic complexity
For example two types of sorting algorithms with O(n) and O(n2)
complexities.
However
This notation does not account for constant factors.
For example
For many cases of n, 1010n is much worse than n2.
36 / 50
Images/ITESM.p
Basically
These complexities allow us to compare algorithms
You can compare 2 algorithms having different asymptotic complexity
For example two types of sorting algorithms with O(n) and O(n2)
complexities.
However
This notation does not account for constant factors.
For example
For many cases of n, 1010n is much worse than n2.
36 / 50
Images/ITESM.p
Outline
1 What the Course is About?
2 What is a Good Algorithm?
Sorting
A Naive Algorithm
Counting Steps
A more realistic step count
Definition of Big O
Meaning for insertion sort
3 Examples of Complexities
Problems Calculating Complexities
37 / 50
Images/ITESM.p
A Huge Problem for calculating complexities
The memory hierachy: Slower Memories as further you go from the
CORE
Main Memory
L3 Cache
L2 Cache L1i Cache
L1d Cache CPU Core
BUS
Note: I will recommend to read “What Every Programmer Should
Know About Memory” by Ulrich Drepper Red Hat, Inc.
38 / 50
Images/ITESM.p
Examples
B-Trees are generalized Binary Search Trees
With element in the nodes sorted in increasing order
39 / 50
Images/ITESM.p
Example
We can improve B-Tree policies to find indexes inside nodes by
Binary Search
Linear Search
40 / 50
Images/ITESM.p
Example
We can improve B-Tree policies to find indexes inside nodes by
Binary Search
Linear Search
40 / 50
Images/ITESM.p
Here, a reasonable assumption!!!
Classic Analysis
Binary Search Faster than Linear Search!!!
Node Structure a(i) ≤ a(i+1) ∀i
However, Core i7 has prefetching
Thus, for a certain size of a node, linear searching will be faster than
binary search due to prefetching hardware!!!
41 / 50
Images/ITESM.p
Here, a reasonable assumption!!!
Classic Analysis
Binary Search Faster than Linear Search!!!
Node Structure a(i) ≤ a(i+1) ∀i
However, Core i7 has prefetching
Thus, for a certain size of a node, linear searching will be faster than
binary search due to prefetching hardware!!!
41 / 50
Images/ITESM.p
Here, a reasonable assumption!!!
Classic Analysis
Binary Search Faster than Linear Search!!!
Node Structure a(i) ≤ a(i+1) ∀i
However, Core i7 has prefetching
Thus, for a certain size of a node, linear searching will be faster than
binary search due to prefetching hardware!!!
41 / 50
Images/ITESM.p
Main Problem
Main problem
Our analysis does not account for this difference in memory access times.
Thus
What do we need?
What?
A way to measure the time in our Java programs.
42 / 50
Images/ITESM.p
Main Problem
Main problem
Our analysis does not account for this difference in memory access times.
Thus
What do we need?
What?
A way to measure the time in our Java programs.
42 / 50
Images/ITESM.p
Main Problem
Main problem
Our analysis does not account for this difference in memory access times.
Thus
What do we need?
What?
A way to measure the time in our Java programs.
42 / 50
Images/ITESM.p
What do we need?
Data
1 Worst-case data
2 Best-case data
3 Average-case data
In addition
A way to measure the time in a machine and language
Problem
We require certain degree of accuracy that we do not have
43 / 50
Images/ITESM.p
What do we need?
Data
1 Worst-case data
2 Best-case data
3 Average-case data
In addition
A way to measure the time in a machine and language
Problem
We require certain degree of accuracy that we do not have
43 / 50
Images/ITESM.p
What do we need?
Data
1 Worst-case data
2 Best-case data
3 Average-case data
In addition
A way to measure the time in a machine and language
Problem
We require certain degree of accuracy that we do not have
43 / 50
Images/ITESM.p
What do we have?
Java Instruction
System.currentTimeMillis()
It returns the current time in milliseconds.
The granularity of the value depends on the underlying
operating system and may be larger.
Yes!!!
The accuracy is not great for it!!!
44 / 50
Images/ITESM.p
What do we have?
Java Instruction
System.currentTimeMillis()
It returns the current time in milliseconds.
The granularity of the value depends on the underlying
operating system and may be larger.
Yes!!!
The accuracy is not great for it!!!
44 / 50
Images/ITESM.p
What do we have?
Java Instruction
System.currentTimeMillis()
It returns the current time in milliseconds.
The granularity of the value depends on the underlying
operating system and may be larger.
Yes!!!
The accuracy is not great for it!!!
44 / 50
Images/ITESM.p
What do we have?
Java Instruction
System.currentTimeMillis()
It returns the current time in milliseconds.
The granularity of the value depends on the underlying
operating system and may be larger.
Yes!!!
The accuracy is not great for it!!!
44 / 50
Images/ITESM.p
Possible Solution
What to do?
Ideas?
What about this logic?
1 Assume that you have a 100 millisecond accuracy in a Linux System.
2 Assume that you want to have a measurement error of 10%.
3 What do we do?
45 / 50
Images/ITESM.p
Possible Solution
What to do?
Ideas?
What about this logic?
1 Assume that you have a 100 millisecond accuracy in a Linux System.
2 Assume that you want to have a measurement error of 10%.
3 What do we do?
45 / 50
Images/ITESM.p
Possible Solution
What to do?
Ideas?
What about this logic?
1 Assume that you have a 100 millisecond accuracy in a Linux System.
2 Assume that you want to have a measurement error of 10%.
3 What do we do?
45 / 50
Images/ITESM.p
Possible Solution
What to do?
Ideas?
What about this logic?
1 Assume that you have a 100 millisecond accuracy in a Linux System.
2 Assume that you want to have a measurement error of 10%.
3 What do we do?
45 / 50
Images/ITESM.p
Simple Idea for Accuracy
If we want to have a 10% error
We need to measure 100% of the total time.
In the case of 100 milliseconds
We need to measure operations for ≥ 1000 milliseconds!!!
Or trueElapsedTime = finishTime - startTime +/- Error
46 / 50
Images/ITESM.p
Simple Idea for Accuracy
If we want to have a 10% error
We need to measure 100% of the total time.
In the case of 100 milliseconds
We need to measure operations for ≥ 1000 milliseconds!!!
Or trueElapsedTime = finishTime - startTime +/- Error
46 / 50
Images/ITESM.p
Simple Idea for Accuracy
If we want to have a 10% error
We need to measure 100% of the total time.
In the case of 100 milliseconds
We need to measure operations for ≥ 1000 milliseconds!!!
Or trueElapsedTime = finishTime - startTime +/- Error
46 / 50
Images/ITESM.p
First Solution
Repeat method until you accumulate enough time
For this, if you have 100 milliseconds for the code to be measured, then
you need a Time≥1000 milliseconds to obtain an accuracy of 10%.
First we device the timing code
47 / 50
Images/ITESM.p
First Solution
Repeat method until you accumulate enough time
For this, if you have 100 milliseconds for the code to be measured, then
you need a Time≥1000 milliseconds to obtain an accuracy of 10%.
First we device the timing code
// g i v e s time i n m i l l i s e c o n d s s i n c e 1/1/1970 GMT
long startTime = System . c u r r e n t T i m e M i l l i s ( ) ;
// code to be timed comes here
long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ;
47 / 50
Images/ITESM.p
What is the problem with this Solution?
PROBLEM!!!
long startTime = System . c u r r e n t T i m e M i l l i s ( ) ;
long counter ;
// Put code to i n i t i a l i z e a [ ] here
// Go f o r randomized a r r a y
do{
counter++;
SomeClass . I n s e r t i o n S o r t (A ) ;
} w h i l e ( System . c u r r e n t T i m e M i l l i s ()− startTime < 1000)
long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ;
f l o a t timeForMethod = (( f l o a t ) elapsedTime )/ counter ;
48 / 50
Images/ITESM.p
Fix
Solution
long startTime = System . c u r r e n t T i m e M i l l i s ( ) ;
long counter ;
do{
counter++;
// Move the code to i n i t i a l i z e a [ ] here
// Go f o r randomized a r r a y
SomeClass . I n s e r t i o n S o r t (A ) ;
} w h i l e ( System . c u r r e n t T i m e M i l l i s ()− startTime < 1000)
long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ;
f l o a t timeForMethod = (( f l o a t ) elapsedTime )/ counter ;
49 / 50
Images/ITESM.p
Another Way to Measure Time
In Unix/Linux Systems, we have the following command
~$ time MyProgram
50 / 50

More Related Content

What's hot

What's hot (20)

Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
7array in c#
7array in c#7array in c#
7array in c#
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
Arrays
ArraysArrays
Arrays
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Array
ArrayArray
Array
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
array
array array
array
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 

Viewers also liked

Preparation Data Structures 02 recursion
Preparation Data Structures 02 recursionPreparation Data Structures 02 recursion
Preparation Data Structures 02 recursionAndres Mendez-Vazquez
 
An introduction to support vector machines
An introduction to support vector machinesAn introduction to support vector machines
An introduction to support vector machinesAndres Mendez-Vazquez
 
07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema Theorem07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema TheoremAndres Mendez-Vazquez
 
Preparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesPreparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesAndres Mendez-Vazquez
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
03 Analysis of Algorithms: Probabilistic Analysis
03 Analysis of Algorithms: Probabilistic Analysis03 Analysis of Algorithms: Probabilistic Analysis
03 Analysis of Algorithms: Probabilistic AnalysisAndres Mendez-Vazquez
 
06 Analysis of Algorithms: Sorting in Linear Time
06 Analysis of Algorithms:  Sorting in Linear Time06 Analysis of Algorithms:  Sorting in Linear Time
06 Analysis of Algorithms: Sorting in Linear TimeAndres Mendez-Vazquez
 
02.03 Artificial Intelligence: Search by Optimization
02.03 Artificial Intelligence: Search by Optimization02.03 Artificial Intelligence: Search by Optimization
02.03 Artificial Intelligence: Search by OptimizationAndres Mendez-Vazquez
 

Viewers also liked (20)

M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
 
Preparation Data Structures 02 recursion
Preparation Data Structures 02 recursionPreparation Data Structures 02 recursion
Preparation Data Structures 02 recursion
 
ELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURESELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURES
 
Data representation UNIT-1
Data representation UNIT-1Data representation UNIT-1
Data representation UNIT-1
 
09 binary trees
09 binary trees09 binary trees
09 binary trees
 
An introduction to support vector machines
An introduction to support vector machinesAn introduction to support vector machines
An introduction to support vector machines
 
07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema Theorem07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema Theorem
 
Preparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesPreparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_types
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
 
14 Skip Lists
14 Skip Lists14 Skip Lists
14 Skip Lists
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
 
03 Analysis of Algorithms: Probabilistic Analysis
03 Analysis of Algorithms: Probabilistic Analysis03 Analysis of Algorithms: Probabilistic Analysis
03 Analysis of Algorithms: Probabilistic Analysis
 
06 Analysis of Algorithms: Sorting in Linear Time
06 Analysis of Algorithms:  Sorting in Linear Time06 Analysis of Algorithms:  Sorting in Linear Time
06 Analysis of Algorithms: Sorting in Linear Time
 
13 Amortized Analysis
13 Amortized Analysis13 Amortized Analysis
13 Amortized Analysis
 
12 Greeddy Method
12 Greeddy Method12 Greeddy Method
12 Greeddy Method
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
08 Hash Tables
08 Hash Tables08 Hash Tables
08 Hash Tables
 
02.03 Artificial Intelligence: Search by Optimization
02.03 Artificial Intelligence: Search by Optimization02.03 Artificial Intelligence: Search by Optimization
02.03 Artificial Intelligence: Search by Optimization
 

Similar to Preparation Data Structures 01 introduction

Lecture-1-Algorithms.pptx
Lecture-1-Algorithms.pptxLecture-1-Algorithms.pptx
Lecture-1-Algorithms.pptxxalahama3
 
Python Peculiarities
Python PeculiaritiesPython Peculiarities
Python Peculiaritiesnoamt
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and reviewAbdullah Al-hazmy
 
Spreadsheets for developers
Spreadsheets for developersSpreadsheets for developers
Spreadsheets for developersFelienne Hermans
 
Csallner algorithms1
Csallner algorithms1Csallner algorithms1
Csallner algorithms1seshagiri rao
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problemecomputernotes
 
Algorithms the fundamentals, For computer Science.ppt
Algorithms the fundamentals, For computer Science.pptAlgorithms the fundamentals, For computer Science.ppt
Algorithms the fundamentals, For computer Science.pptCarloCimacio
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Intro to DSAA.ppt
Intro to DSAA.pptIntro to DSAA.ppt
Intro to DSAA.pptjumar dimas
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming hccit
 

Similar to Preparation Data Structures 01 introduction (20)

lec1.ppt
lec1.pptlec1.ppt
lec1.ppt
 
Lecture-1-Algorithms.pptx
Lecture-1-Algorithms.pptxLecture-1-Algorithms.pptx
Lecture-1-Algorithms.pptx
 
Basic concepts of statistics
Basic concepts of statistics Basic concepts of statistics
Basic concepts of statistics
 
Basic concepts of statistics
Basic concepts of statistics Basic concepts of statistics
Basic concepts of statistics
 
Basic concepts of statistics
Basic concepts of statistics Basic concepts of statistics
Basic concepts of statistics
 
Python Peculiarities
Python PeculiaritiesPython Peculiarities
Python Peculiarities
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 
Spreadsheets for developers
Spreadsheets for developersSpreadsheets for developers
Spreadsheets for developers
 
Lesson 18-20.pptx
Lesson 18-20.pptxLesson 18-20.pptx
Lesson 18-20.pptx
 
Sorting
SortingSorting
Sorting
 
Csallner algorithms1
Csallner algorithms1Csallner algorithms1
Csallner algorithms1
 
Oct27
Oct27Oct27
Oct27
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
Algorithms the fundamentals, For computer Science.ppt
Algorithms the fundamentals, For computer Science.pptAlgorithms the fundamentals, For computer Science.ppt
Algorithms the fundamentals, For computer Science.ppt
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Intro to DSAA.ppt
Intro to DSAA.pptIntro to DSAA.ppt
Intro to DSAA.ppt
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
 

More from Andres Mendez-Vazquez

01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectorsAndres Mendez-Vazquez
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issuesAndres Mendez-Vazquez
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiationAndres Mendez-Vazquez
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep LearningAndres Mendez-Vazquez
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learningAndres Mendez-Vazquez
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusAndres Mendez-Vazquez
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusAndres Mendez-Vazquez
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesAndres Mendez-Vazquez
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variationsAndres Mendez-Vazquez
 

More from Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
 
Zetta global
Zetta globalZetta global
Zetta global
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
 

Recently uploaded

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Preparation Data Structures 01 introduction

  • 2. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 2 / 50
  • 3. Images/ITESM.p Introduction Data Manipulation Data structures is concerned with the representation and manipulation of data. Further All programs manipulate data. Thus!!! So, all programs represent data in some way. Data manipulation requires a data structure and an algorithm!!! 3 / 50
  • 4. Images/ITESM.p Introduction Data Manipulation Data structures is concerned with the representation and manipulation of data. Further All programs manipulate data. Thus!!! So, all programs represent data in some way. Data manipulation requires a data structure and an algorithm!!! 3 / 50
  • 5. Images/ITESM.p Introduction Data Manipulation Data structures is concerned with the representation and manipulation of data. Further All programs manipulate data. Thus!!! So, all programs represent data in some way. Data manipulation requires a data structure and an algorithm!!! 3 / 50
  • 6. Images/ITESM.p Introduction Data Manipulation Data structures is concerned with the representation and manipulation of data. Further All programs manipulate data. Thus!!! So, all programs represent data in some way. Data manipulation requires a data structure and an algorithm!!! 3 / 50
  • 7. Images/ITESM.p Examples Data Bases Using B-trees for fast access to the records!!! 4 / 50
  • 8. Images/ITESM.p Example Storing Sparse Matrices 5x5 Matrix Numeric Elements Empty Elements Sparse Matrix Why? Reduce the amount memory used for storage!!! 5 / 50
  • 9. Images/ITESM.p Example Storing Sparse Matrices 5x5 Matrix Numeric Elements Empty Elements Sparse Matrix Why? Reduce the amount memory used for storage!!! 5 / 50
  • 11. Images/ITESM.p What is the course about? First Understanding Data Structure and Algorithms needed to develop programs for data manipulation. Why? The study of Data Structures and Algorithms is fundamental to Computer Science. 7 / 50
  • 12. Images/ITESM.p What is the course about? First Understanding Data Structure and Algorithms needed to develop programs for data manipulation. Why? The study of Data Structures and Algorithms is fundamental to Computer Science. 7 / 50
  • 13. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 8 / 50
  • 14. Images/ITESM.p In sorting, we want to have the following Rearrange a sequence of numbers 9,3,4,2,1 Into an increasing sequence 1, 2, 3, 4, 9 Or Into a decreasing sequence 9, 4, 3, 2, 1 9 / 50
  • 15. Images/ITESM.p In sorting, we want to have the following Rearrange a sequence of numbers 9,3,4,2,1 Into an increasing sequence 1, 2, 3, 4, 9 Or Into a decreasing sequence 9, 4, 3, 2, 1 9 / 50
  • 16. Images/ITESM.p In sorting, we want to have the following Rearrange a sequence of numbers 9,3,4,2,1 Into an increasing sequence 1, 2, 3, 4, 9 Or Into a decreasing sequence 9, 4, 3, 2, 1 9 / 50
  • 17. Images/ITESM.p Notation For now, we will assume that the data It is an array A. Meaning item 9 3 4 2 1 index 0 1 2 3 4 Thus If we need to reference elements on the array through an index, we use the following notation A [index] (1) 10 / 50
  • 18. Images/ITESM.p Notation For now, we will assume that the data It is an array A. Meaning item 9 3 4 2 1 index 0 1 2 3 4 Thus If we need to reference elements on the array through an index, we use the following notation A [index] (1) 10 / 50
  • 19. Images/ITESM.p Notation For now, we will assume that the data It is an array A. Meaning item 9 3 4 2 1 index 0 1 2 3 4 Thus If we need to reference elements on the array through an index, we use the following notation A [index] (1) 10 / 50
  • 20. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 11 / 50
  • 21. Images/ITESM.p Naive Algorithm What if we do the following 1 Pick an element in the array A. 2 Put that element in the correct position. Thus We will concentrate first in inserting the element in the correct position For this imagine the following We already have an array A = [1|3|6|4| − |−] where “-” represents null elements. 12 / 50
  • 22. Images/ITESM.p Naive Algorithm What if we do the following 1 Pick an element in the array A. 2 Put that element in the correct position. Thus We will concentrate first in inserting the element in the correct position For this imagine the following We already have an array A = [1|3|6|4| − |−] where “-” represents null elements. 12 / 50
  • 23. Images/ITESM.p Naive Algorithm What if we do the following 1 Pick an element in the array A. 2 Put that element in the correct position. Thus We will concentrate first in inserting the element in the correct position For this imagine the following We already have an array A = [1|3|6|4| − |−] where “-” represents null elements. 12 / 50
  • 24. Images/ITESM.p Naive Algorithm What if we do the following 1 Pick an element in the array A. 2 Put that element in the correct position. Thus We will concentrate first in inserting the element in the correct position For this imagine the following We already have an array A = [1|3|6|4| − |−] where “-” represents null elements. 12 / 50
  • 25. Images/ITESM.p Thus Where do we start comparing to insert? Ideas? Maybe Let us do it with A = [1|3|6|4| − |−] 13 / 50
  • 26. Images/ITESM.p Thus Where do we start comparing to insert? Ideas? Maybe From the right!!! After all we have space Let us do it with A = [1|3|6|4| − |−] 13 / 50
  • 27. Images/ITESM.p Thus Where do we start comparing to insert? Ideas? Maybe From the right!!! After all we have space Let us do it with A = [1|3|6|4| − |−] 13 / 50
  • 28. Images/ITESM.p What about the code? What do we use for going through a sequence? Ideas? In addition, we need to make space For the new item. Code 14 / 50
  • 29. Images/ITESM.p What about the code? What do we use for going through a sequence? Ideas? In addition, we need to make space For the new item. Code 14 / 50
  • 30. Images/ITESM.p What about the code? What do we use for going through a sequence? Ideas? In addition, we need to make space For the new item. Code p r i v a t e i n t [ ] i n s e r t ( i n t [ ] A, i n t t ){ // Extra V a r i a b l e s i n t j ; // I n s e r t i n t o A [ 0 : i −1] f o r ( j = A. lenght −1; j >=0 && t<A[ j ] ; j −−){ // s h i f t to the r i g h t A[ j +1]=A[ j ] ; } A[ j +1]=t ; r e t u r n A; } 14 / 50
  • 31. Images/ITESM.p Ok, We have that...Now what? How do we use this piece of code for the insertion sort? Ideas? Problem with the code!! You require that the array where you insert to be sorted!!! Look at this!!! At the Board... Thus How do we solve this problem? 15 / 50
  • 32. Images/ITESM.p Ok, We have that...Now what? How do we use this piece of code for the insertion sort? Ideas? Problem with the code!! You require that the array where you insert to be sorted!!! Look at this!!! At the Board... Thus How do we solve this problem? 15 / 50
  • 33. Images/ITESM.p Ok, We have that...Now what? How do we use this piece of code for the insertion sort? Ideas? Problem with the code!! You require that the array where you insert to be sorted!!! Look at this!!! At the Board... Thus How do we solve this problem? 15 / 50
  • 34. Images/ITESM.p Then, Insertion Sort works like this First Start with a sequence of size 1. After all an array with one element is sorted!!! Second Repeatedly insert remaining elements Example Sort 7, 3, 5, 6, 1 16 / 50
  • 35. Images/ITESM.p Then, Insertion Sort works like this First Start with a sequence of size 1. After all an array with one element is sorted!!! Second Repeatedly insert remaining elements Example Sort 7, 3, 5, 6, 1 16 / 50
  • 36. Images/ITESM.p Then, Insertion Sort works like this First Start with a sequence of size 1. After all an array with one element is sorted!!! Second Repeatedly insert remaining elements Example Sort 7, 3, 5, 6, 1 16 / 50
  • 37. Images/ITESM.p Final Code Something Notable // Sort A assume i s f u l l p u b l i c i n t [ ] I n s e r t i o n S o r t ( i n t [ ] A){ // Extra Space i n t B [ ] = new i n t [A. l e n g t h ] ; // I n i t Array B B[0]=A [ 0 ] ; i n t s i z e = 1; i n t j , t ; f o r ( i n t i = 1; i < A. l e n g t h ; i ++){ t = A[ i ] ; f o r ( j = s i z e −1; j >=0 && t<B[ j ] ; j −−) { // s h i f t to the r i g h t B[ j +1]=B[ j ] ; } B[ j +1]=t ; s i z e ++; } r e t u r n B; } 17 / 50
  • 38. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 18 / 50
  • 39. Images/ITESM.p Question: Which Complexity You Have with Insertion Sort? After all you have!!! Time Complexity!!! For this, we have Time Complexity Techniques: Count a particular operation Count number of steps Asymptotic complexity 19 / 50
  • 40. Images/ITESM.p Question: Which Complexity You Have with Insertion Sort? After all you have!!! Time Complexity!!! For this, we have Time Complexity Techniques: Count a particular operation Count number of steps Asymptotic complexity 19 / 50
  • 41. Images/ITESM.p Question: Which Complexity You Have with Insertion Sort? After all you have!!! Time Complexity!!! For this, we have Time Complexity Techniques: Count a particular operation Count number of steps Asymptotic complexity 19 / 50
  • 42. Images/ITESM.p Question: Which Complexity You Have with Insertion Sort? After all you have!!! Time Complexity!!! For this, we have Time Complexity Techniques: Count a particular operation Count number of steps Asymptotic complexity 19 / 50
  • 43. Images/ITESM.p Question: Which Complexity You Have with Insertion Sort? After all you have!!! Time Complexity!!! For this, we have Time Complexity Techniques: Count a particular operation Count number of steps Asymptotic complexity 19 / 50
  • 44. Images/ITESM.p Basically, we will use the second one First Look at this part of the code f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Then How many comparisons are made? 20 / 50
  • 45. Images/ITESM.p Basically, we will use the second one First Look at this part of the code f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Then How many comparisons are made? 20 / 50
  • 46. Images/ITESM.p The Possible Cases Worst-case count Maximum count Best-case count Minimum count In addition, we have Average Count 21 / 50
  • 47. Images/ITESM.p The Possible Cases Worst-case count Maximum count Best-case count Minimum count In addition, we have Average Count 21 / 50
  • 48. Images/ITESM.p The Possible Cases Worst-case count Maximum count Best-case count Minimum count In addition, we have Average Count 21 / 50
  • 49. Images/ITESM.p Example: Worst-Case For the Code Code, Look at the red compares f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Case I If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares. What about the general case If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares. 22 / 50
  • 50. Images/ITESM.p Example: Worst-Case For the Code Code, Look at the red compares f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Case I If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares. What about the general case If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares. 22 / 50
  • 51. Images/ITESM.p Example: Worst-Case For the Code Code, Look at the red compares f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Case I If B = [1, 2, 3, 4] and t = 0 =⇒ 4 compares. What about the general case If B = [1, 2, 3, ..., i] and t = 0 =⇒ i compares. 22 / 50
  • 52. Images/ITESM.p Worst-Case For An Almost Final Version Simplified Version Remember s i z e i s the s i z e of B f o r ( i = 2; i < A. l e n g t h ; i++ ) f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Worst Case for the Outer Loop 1 Outer loop takes n steps What about the inner loop? Answer 23 / 50
  • 53. Images/ITESM.p Worst-Case For An Almost Final Version Simplified Version Remember s i z e i s the s i z e of B f o r ( i = 2; i < A. l e n g t h ; i++ ) f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Worst Case for the Outer Loop 1 Outer loop takes n steps What about the inner loop? Answer 23 / 50
  • 54. Images/ITESM.p Worst-Case For An Almost Final Version Simplified Version Remember s i z e i s the s i z e of B f o r ( i = 2; i < A. l e n g t h ; i++ ) f o r ( j = s i z e −1; j >=0 && t<B[j] ; j −−) B[ j +1]=B[ j ] ; Worst Case for the Outer Loop 1 Outer loop takes n steps What about the inner loop? Answer Number of steps in the inner loop = size+1 23 / 50
  • 55. Images/ITESM.p What is the range of j? Very Simple For the first step j = 1 − 1 =⇒Number of Steps = 2 For the last step j = n − 1 − 1 =⇒Number of Steps = n Total Compares 2 + 3 + 4 + ... + n = n (n + 1) 2 − 1 (2) 24 / 50
  • 56. Images/ITESM.p What is the range of j? Very Simple For the first step j = 1 − 1 =⇒Number of Steps = 2 For the last step j = n − 1 − 1 =⇒Number of Steps = n Total Compares 2 + 3 + 4 + ... + n = n (n + 1) 2 − 1 (2) 24 / 50
  • 57. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 25 / 50
  • 58. Images/ITESM.p A more realistic step count Counting when A.length = n // Sort A assume i s f u l l p u b l i c i n t [ ] I n s e r t i o n S o r t ( i n t [ ] A){ Step // I n i t i a l V a r i a b l e s 0 i n t B [ ] = new i n t [A. l e n g t h ] ; 1 i n t s i z e = 1; 1 i n t i , j , t ; 1 // I n i t i a l i z e the Array B 0 B[0]=A [ 0 ] ; 1 f o r ( i = 1; i < A. l e n g t h ; i ++){ n t = A[ i ] ; n−1 f o r ( j=s i z e −1; j>=0&&t<B[ j ] ; j −−) i +1 { // s h i f t to the r i g h t 0 B[ j +1]=B[ j ] ; } i B[ j +1]=t ; n−1 s i z e ++; n−1 } r e t u r n B; 1 } 26 / 50
  • 59. Images/ITESM.p The Result Step count for body of for loop is 6 + 3 (n − 1) + n + n−1 i=1 (i + 1) + n−1 j=1 (i) (3) The summation They have the quadratic terms n2. Complexity Insertion sort complexity is O n2 27 / 50
  • 60. Images/ITESM.p The Result Step count for body of for loop is 6 + 3 (n − 1) + n + n−1 i=1 (i + 1) + n−1 j=1 (i) (3) The summation They have the quadratic terms n2. Complexity Insertion sort complexity is O n2 27 / 50
  • 61. Images/ITESM.p The Result Step count for body of for loop is 6 + 3 (n − 1) + n + n−1 i=1 (i + 1) + n−1 j=1 (i) (3) The summation They have the quadratic terms n2. Complexity Insertion sort complexity is O n2 27 / 50
  • 62. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 28 / 50
  • 63. Images/ITESM.p Definition of Big O Definition For a given function g(n) O(g(n)) ={f (n)| There exists c > 0 and n0 > 0 s.t. 0 ≤ f (n) ≤ cg(n) ∀n ≥ n0} Graphically 29 / 50
  • 64. Images/ITESM.p Definition of Big O Definition For a given function g(n) O(g(n)) ={f (n)| There exists c > 0 and n0 > 0 s.t. 0 ≤ f (n) ≤ cg(n) ∀n ≥ n0} Graphically 29 / 50
  • 65. Images/ITESM.p What? The term n0 It tells you when for the following n s you will have that f (n) ≤ cg(n) What about the so called c It can be seen a way to “increase” or “decrease” the height of the function!!! 30 / 50
  • 66. Images/ITESM.p What? The term n0 It tells you when for the following n s you will have that f (n) ≤ cg(n) What about the so called c It can be seen a way to “increase” or “decrease” the height of the function!!! 30 / 50
  • 67. Images/ITESM.p What? The term n0 It tells you when for the following n s you will have that f (n) ≤ cg(n) What about the so called c It can be seen a way to “increase” or “decrease” the height of the function!!! 30 / 50
  • 68. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 31 / 50
  • 69. Images/ITESM.p What does this means for insertion sort? We have 6 + 3 (n − 1) + n + n−1 i=1 (i + 1) + n−1 j=1 (i) = ... 3 + 4n + n (n − 1) 2 + n − 1 + n (n − 1) 2 = ... 2 + 5n + n(n − 1) = ... n2 + 4n + 2 ≤ n2 + 4n2 + 2n2 Thus n2 + 4n + 2 ≤ 7n2 (4) With Tinsertion(n) = n2 + 4n + 2 describing the number of steps for insertion when we have n numbers. 32 / 50
  • 70. Images/ITESM.p What does this means for insertion sort? We have 6 + 3 (n − 1) + n + n−1 i=1 (i + 1) + n−1 j=1 (i) = ... 3 + 4n + n (n − 1) 2 + n − 1 + n (n − 1) 2 = ... 2 + 5n + n(n − 1) = ... n2 + 4n + 2 ≤ n2 + 4n2 + 2n2 Thus n2 + 4n + 2 ≤ 7n2 (4) With Tinsertion(n) = n2 + 4n + 2 describing the number of steps for insertion when we have n numbers. 32 / 50
  • 71. Images/ITESM.p Actually For n0 = 2 22 + 4 × 2 + 2 = 14 < 7 × 22 = 28 (5) Graphically 33 / 50
  • 72. Images/ITESM.p Actually For n0 = 2 22 + 4 × 2 + 2 = 14 < 7 × 22 = 28 (5) Graphically 33 / 50
  • 73. Images/ITESM.p Meaning First Time or number of operations does not exceed cn2 for a constant c on any input of size n (n suitably large). Questions Is O(n2) too much time? Is the algorithm practical? For this imagine, we have a machine able to make 109instructions/seconds 34 / 50
  • 74. Images/ITESM.p Meaning First Time or number of operations does not exceed cn2 for a constant c on any input of size n (n suitably large). Questions Is O(n2) too much time? Is the algorithm practical? For this imagine, we have a machine able to make 109instructions/seconds 34 / 50
  • 75. Images/ITESM.p Meaning First Time or number of operations does not exceed cn2 for a constant c on any input of size n (n suitably large). Questions Is O(n2) too much time? Is the algorithm practical? For this imagine, we have a machine able to make 109instructions/seconds 34 / 50
  • 76. Images/ITESM.p Meaning First Time or number of operations does not exceed cn2 for a constant c on any input of size n (n suitably large). Questions Is O(n2) too much time? Is the algorithm practical? For this imagine, we have a machine able to make 109instructions/seconds 34 / 50
  • 77. Images/ITESM.p Then We have the following n n n log n n2 n3 n4 1000 1 micros 10 micros 1 milis 1 second 17 minutes 10,000 10 micros 130 micros 100 milis 17 minutes 116 days 106 1 milis 20 milis 17 minutes 32 years 3 × 107 years It is much worse 35 / 50
  • 78. Images/ITESM.p Then We have the following n n n log n n2 n3 n4 1000 1 micros 10 micros 1 milis 1 second 17 minutes 10,000 10 micros 130 micros 100 milis 17 minutes 116 days 106 1 milis 20 milis 17 minutes 32 years 3 × 107 years It is much worse n n10 2n 1000 3.2 × 1013 years 3.2 × 10283 years 10,000 ??? ??? 106 ????? ????? The Reign of the Non Polynomial Algorithms 35 / 50
  • 79. Images/ITESM.p Basically These complexities allow us to compare algorithms You can compare 2 algorithms having different asymptotic complexity For example two types of sorting algorithms with O(n) and O(n2) complexities. However This notation does not account for constant factors. For example For many cases of n, 1010n is much worse than n2. 36 / 50
  • 80. Images/ITESM.p Basically These complexities allow us to compare algorithms You can compare 2 algorithms having different asymptotic complexity For example two types of sorting algorithms with O(n) and O(n2) complexities. However This notation does not account for constant factors. For example For many cases of n, 1010n is much worse than n2. 36 / 50
  • 81. Images/ITESM.p Basically These complexities allow us to compare algorithms You can compare 2 algorithms having different asymptotic complexity For example two types of sorting algorithms with O(n) and O(n2) complexities. However This notation does not account for constant factors. For example For many cases of n, 1010n is much worse than n2. 36 / 50
  • 82. Images/ITESM.p Outline 1 What the Course is About? 2 What is a Good Algorithm? Sorting A Naive Algorithm Counting Steps A more realistic step count Definition of Big O Meaning for insertion sort 3 Examples of Complexities Problems Calculating Complexities 37 / 50
  • 83. Images/ITESM.p A Huge Problem for calculating complexities The memory hierachy: Slower Memories as further you go from the CORE Main Memory L3 Cache L2 Cache L1i Cache L1d Cache CPU Core BUS Note: I will recommend to read “What Every Programmer Should Know About Memory” by Ulrich Drepper Red Hat, Inc. 38 / 50
  • 84. Images/ITESM.p Examples B-Trees are generalized Binary Search Trees With element in the nodes sorted in increasing order 39 / 50
  • 85. Images/ITESM.p Example We can improve B-Tree policies to find indexes inside nodes by Binary Search Linear Search 40 / 50
  • 86. Images/ITESM.p Example We can improve B-Tree policies to find indexes inside nodes by Binary Search Linear Search 40 / 50
  • 87. Images/ITESM.p Here, a reasonable assumption!!! Classic Analysis Binary Search Faster than Linear Search!!! Node Structure a(i) ≤ a(i+1) ∀i However, Core i7 has prefetching Thus, for a certain size of a node, linear searching will be faster than binary search due to prefetching hardware!!! 41 / 50
  • 88. Images/ITESM.p Here, a reasonable assumption!!! Classic Analysis Binary Search Faster than Linear Search!!! Node Structure a(i) ≤ a(i+1) ∀i However, Core i7 has prefetching Thus, for a certain size of a node, linear searching will be faster than binary search due to prefetching hardware!!! 41 / 50
  • 89. Images/ITESM.p Here, a reasonable assumption!!! Classic Analysis Binary Search Faster than Linear Search!!! Node Structure a(i) ≤ a(i+1) ∀i However, Core i7 has prefetching Thus, for a certain size of a node, linear searching will be faster than binary search due to prefetching hardware!!! 41 / 50
  • 90. Images/ITESM.p Main Problem Main problem Our analysis does not account for this difference in memory access times. Thus What do we need? What? A way to measure the time in our Java programs. 42 / 50
  • 91. Images/ITESM.p Main Problem Main problem Our analysis does not account for this difference in memory access times. Thus What do we need? What? A way to measure the time in our Java programs. 42 / 50
  • 92. Images/ITESM.p Main Problem Main problem Our analysis does not account for this difference in memory access times. Thus What do we need? What? A way to measure the time in our Java programs. 42 / 50
  • 93. Images/ITESM.p What do we need? Data 1 Worst-case data 2 Best-case data 3 Average-case data In addition A way to measure the time in a machine and language Problem We require certain degree of accuracy that we do not have 43 / 50
  • 94. Images/ITESM.p What do we need? Data 1 Worst-case data 2 Best-case data 3 Average-case data In addition A way to measure the time in a machine and language Problem We require certain degree of accuracy that we do not have 43 / 50
  • 95. Images/ITESM.p What do we need? Data 1 Worst-case data 2 Best-case data 3 Average-case data In addition A way to measure the time in a machine and language Problem We require certain degree of accuracy that we do not have 43 / 50
  • 96. Images/ITESM.p What do we have? Java Instruction System.currentTimeMillis() It returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger. Yes!!! The accuracy is not great for it!!! 44 / 50
  • 97. Images/ITESM.p What do we have? Java Instruction System.currentTimeMillis() It returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger. Yes!!! The accuracy is not great for it!!! 44 / 50
  • 98. Images/ITESM.p What do we have? Java Instruction System.currentTimeMillis() It returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger. Yes!!! The accuracy is not great for it!!! 44 / 50
  • 99. Images/ITESM.p What do we have? Java Instruction System.currentTimeMillis() It returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger. Yes!!! The accuracy is not great for it!!! 44 / 50
  • 100. Images/ITESM.p Possible Solution What to do? Ideas? What about this logic? 1 Assume that you have a 100 millisecond accuracy in a Linux System. 2 Assume that you want to have a measurement error of 10%. 3 What do we do? 45 / 50
  • 101. Images/ITESM.p Possible Solution What to do? Ideas? What about this logic? 1 Assume that you have a 100 millisecond accuracy in a Linux System. 2 Assume that you want to have a measurement error of 10%. 3 What do we do? 45 / 50
  • 102. Images/ITESM.p Possible Solution What to do? Ideas? What about this logic? 1 Assume that you have a 100 millisecond accuracy in a Linux System. 2 Assume that you want to have a measurement error of 10%. 3 What do we do? 45 / 50
  • 103. Images/ITESM.p Possible Solution What to do? Ideas? What about this logic? 1 Assume that you have a 100 millisecond accuracy in a Linux System. 2 Assume that you want to have a measurement error of 10%. 3 What do we do? 45 / 50
  • 104. Images/ITESM.p Simple Idea for Accuracy If we want to have a 10% error We need to measure 100% of the total time. In the case of 100 milliseconds We need to measure operations for ≥ 1000 milliseconds!!! Or trueElapsedTime = finishTime - startTime +/- Error 46 / 50
  • 105. Images/ITESM.p Simple Idea for Accuracy If we want to have a 10% error We need to measure 100% of the total time. In the case of 100 milliseconds We need to measure operations for ≥ 1000 milliseconds!!! Or trueElapsedTime = finishTime - startTime +/- Error 46 / 50
  • 106. Images/ITESM.p Simple Idea for Accuracy If we want to have a 10% error We need to measure 100% of the total time. In the case of 100 milliseconds We need to measure operations for ≥ 1000 milliseconds!!! Or trueElapsedTime = finishTime - startTime +/- Error 46 / 50
  • 107. Images/ITESM.p First Solution Repeat method until you accumulate enough time For this, if you have 100 milliseconds for the code to be measured, then you need a Time≥1000 milliseconds to obtain an accuracy of 10%. First we device the timing code 47 / 50
  • 108. Images/ITESM.p First Solution Repeat method until you accumulate enough time For this, if you have 100 milliseconds for the code to be measured, then you need a Time≥1000 milliseconds to obtain an accuracy of 10%. First we device the timing code // g i v e s time i n m i l l i s e c o n d s s i n c e 1/1/1970 GMT long startTime = System . c u r r e n t T i m e M i l l i s ( ) ; // code to be timed comes here long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ; 47 / 50
  • 109. Images/ITESM.p What is the problem with this Solution? PROBLEM!!! long startTime = System . c u r r e n t T i m e M i l l i s ( ) ; long counter ; // Put code to i n i t i a l i z e a [ ] here // Go f o r randomized a r r a y do{ counter++; SomeClass . I n s e r t i o n S o r t (A ) ; } w h i l e ( System . c u r r e n t T i m e M i l l i s ()− startTime < 1000) long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ; f l o a t timeForMethod = (( f l o a t ) elapsedTime )/ counter ; 48 / 50
  • 110. Images/ITESM.p Fix Solution long startTime = System . c u r r e n t T i m e M i l l i s ( ) ; long counter ; do{ counter++; // Move the code to i n i t i a l i z e a [ ] here // Go f o r randomized a r r a y SomeClass . I n s e r t i o n S o r t (A ) ; } w h i l e ( System . c u r r e n t T i m e M i l l i s ()− startTime < 1000) long elapsedTime = System . c u r r e n t T i m e M i l l i s ()− startTime ; f l o a t timeForMethod = (( f l o a t ) elapsedTime )/ counter ; 49 / 50
  • 111. Images/ITESM.p Another Way to Measure Time In Unix/Linux Systems, we have the following command ~$ time MyProgram 50 / 50