diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 4292a1b..3120ebd 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -380,3 +380,111 @@ fn insertion_sort(array: &mut [i32]) { } } ``` + +## Recursion + +### Merge sort + +Merge sort is a recursive sorting algorithm with the following pseudocode: + +- If the array length is one or less, do not modify the array +- Otherwise, split the array into two halves and call merge sort on both halves +- Merge the split arrays together in sorted order (adding each in sequence such that it is sorted) + +```cpp +void merge_sort( double array[], std::size_t capacity ) { + if ( capacity <= 1 ) { + return; + } else { + std::size_t capacity_1{ capacity/2 }; + std::size_t capacity_2{ capacity - capacity_1 }; + + merge_sort( array, capacity_1 ); + merge_sort( array + capacity_1, capacity_2 ); + + merge( array, capacity_1, capacity_2 ); + } +} + +void merge( double array[], std::size_t cap_1, + std::size_t cap_2 ) { + double tmp_array[cap_1 + cap_2]; + + std::size_t k1{0}; + std::size_t k2{cap_1}; + std::size_t kt{0}; + + // As long as not everything in each half is not + // copied over, copy the next smallest entry into the + // temporary array. + while ( (k1 < cap_1) && (k2 < cap_1 + cap_2 ) ) { + if ( array[k1] <= array[k2] ) { + tmp_array[kt] = array[k1]; + ++k1; + } else { + tmp_array[kt] = array[k2]; + ++k2; + } + + ++kt; + } + + // Copy all entries left from the left half (if any) + // to the temporary array. + while ( k1 < cap_1 ) { + tmp_array[kt] = array[k1]; + ++k1; + ++kt; + } + + // Copy all entries left from the right half (if any) + // to the temporary array. + while ( k2 < cap_1 + cap_2 ) { + tmp_array[kt] = array[k2]; + ++k2; + ++kt; + } + + // Copy all the entries back to the original array. + for ( std::size_t k{0}; k < (cap_1 + cap_2); ++k ) { + array[k] = tmp_array[k]; + } + +} +``` + +## Classes + +By convention, class member variables are suffixed with an underscore. + +Classes inherently have two default constructors — one if passed another version of itself and one if the user does not define one, using the list of `public` variables. + +!!! example + the following initialisers both do the same thing — they both copy `earth` into a new variable (not by reference). + + ```cpp + Body earth{}; + + Body tmp{earth}; + Body tmp2 = earth; + ``` + +### Namespaces + +Namespaces allow definitions to be scoped, such as `std`. + +```cpp +namespace eggy { + std::string name{"eggy"}; + std::string get_name() { + return eggy::name; + } +} +``` + +Namespaces can also be nested within namespaces. + +!!! warning + `std::cout` does weird shenanigans that passes itself to every function afterward, such as `std::endl`. + + This means that `std::cout << std::endl;` is equivalent to `std::endl(std::cout);`.