Last session was about data types and data structures.
Some data types…:
Tantau (2016)
…and some data structures:
Operation | Arrays | Lists | Sets |
---|---|---|---|
Add item to beginning or end | |||
Access first or last item | |||
Access item by index | |||
Store only unique values | |||
Efficient test for membership |
Why should we care?
Clever organization of your data will help you find things faster.
What do we actually want to find?
Given an array containing some values,
we could search for a
specific value.
Given an array containing some values, we could search
About the inputs and outputs:
We search for | Inputs | Outputs |
---|---|---|
a single value | array + single value | one array-position |
all values | array + single value | all array-positions |
a single value with a characteristic | array + characteristic | one array-position |
all values with a characteristic | array + characteristic | all array-posistions |
In general, there are two approaches to searching:
Linear Search in pseudo code:
procedure linear_search (list, value)
set i to 0
set n to length of list
while i < n
do
if (list at i) = value, terminate and return i
increment i by 1
done
terminate unsuccessfully
end procedure
Consider this example:
How many comparisons are needed to find
How many comparisons are needed
…in the best case? | \(O(1)\) |
…in the worst case? | \(O(n)\) |
…on average? | \(O(n)\) |
Regarding \(O(n)\) in the average case:
\[ \frac{ n+1 }{ 2 } \]
Summarizing linear search:
Do you still know these things?
Ancient storage of knowledge, usually kept on shelves
Space complexity highly inefficient
Some examples had a special organization of knowledge: