Basic algorithms - NormandaleWells/CSn GitHub Wiki
This section introduces some very basic array-based algorithms. We'll see that we can put these simple algorithms to use in creating more complex algorithms and data structures. Also, as we go through the topics in CS1, we'll come back to these often and update them to reflect what we've learned.
We're purposely ignoring the fact that most of these algorithms are available in the standard libraries of most languages, since the purpose here is to show how they're implemented, and how to use them to get useful work done. They're also simple enough to provide good examples when discussing preconditions, loop invariants, and generic coding. When writing in, say, C++, you're advised to use the versions in the <algorithms>
header rather than these.
The algorithms we'll be studying are:
-
find(A, v)
- find first occurrence ofv
inA
-
count(A, v)
- count the number of items inA
equal tov
-
min_element(A)
- find the minimum element ofA
-
max_element(A)
- find the maximum element ofA
-
swap(A, idx1, idx2)
- exchangeA[idx1]
andA[idx2]
-
rotate_left(A)
- rotate elements ofA
one element to the left -
rotate_right(A)
- rotate elements ofA
one element to the right
Our initial versions will work only with arrays of integers; we'll create generic versions later on.
In later sections, we'll add these others:
-
is_sorted(A)
- determine if arrayA
is sorted (ascending) -
selection_sort(A)
- sort arrayA
into ascending order -
insertion_sort(A)
- sort arrayA
into ascending order -
lower_bound(A, v)
- find the first array element inA
greater than or equal tov
-
upper_bound(A, v)
- find the first array element inA
strictly greater thanv
We'll revisit these basic algorithms often, to do such things as:
- Implement versions that operate on a subrange of the array
- Create generic versions
- Document preconditions
- Document loop invariants
- Work with other conditions (predicates) and comparisons
Finally, these algorithms may be used as homework assignments:
-
any_of(A, v)
- returntrue
if 'A' contains at least one occurrence ofv
,false
otherwise -
all_of(A, v)
- returntrue
if every element ofA
is equal tov
, false otherwise -
none_of(A, v)
- returntrue
if no element ofA
is equal tov
, false otherwise -
fill(A, v)
- fillA
with copies ofv
-
accumulate(A)
- add all the elements ofA
and return the result -
reverse(A)
- reverse the elements ofA
-
rotate(A, lo, mid, hi)
- rotate elements ofA[lo,hi)
so thatA[mid]
moves toA[lo]
Note that among the first three (any_of()
, all_of()
, and none_of()
), two are exact opposites of each other; that is, any inputs for which one returns true
, the other will return false
, and vice versa. And they are not the two you might first think!