ece150: add sorting
This commit is contained in:
parent
b01082797c
commit
af6b2adbb2
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user