diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index fd3e70b..4292a1b 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -339,4 +339,44 @@ Pointers to `const` values must also be `const`. int const *p_x{&x}; ``` - +## Sorting algorithms + +### Selection sort + +Selection sort takes the largest item in the array each time and adds it to the end. + +```rust +fn selection_sort(array: &mut [i32]) { + for i in (0..array.len()).rev() { + let mut max_index = 0; + for j in 0..i + 1 { + if array[j] > array[max_index] { + max_index = j; + } + } + let _ = &array.swap(i, max_index); + } +} +``` + +### Insertion sort + +Insertion sort assumes the first element of the array is sorted and expands that partition by moving each element afterward to the correct spot. + +```rust +fn insertion_sort(array: &mut [i32]) { + for i in 1..array.len() { + let mut temp = array[0]; + for j in 0..i { + if array[j] < array[i] { + temp = array[i]; + for k in (j..i).rev() { + array[k + 1] = array[k] + } + array[j] = temp; + break; + } + } + } +} +```