ece150: add sorting

This commit is contained in:
eggy 2022-11-05 12:43:03 -04:00
parent b01082797c
commit af6b2adbb2

View File

@ -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;
}
}
}
}
```