diff --git a/challenges/sorting-algorithms/solutions/rust/insertion-sort/README.md b/challenges/sorting-algorithms/solutions/rust/insertion-sort/README.md new file mode 100644 index 0000000..2ed7f53 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/rust/insertion-sort/README.md @@ -0,0 +1,3 @@ +# sorting-algorithms/rust/insertion-sort + +Created by [@Divlo](https://github.com/Divlo) on 8 March 2022. diff --git a/challenges/sorting-algorithms/solutions/rust/insertion-sort/solution.rs b/challenges/sorting-algorithms/solutions/rust/insertion-sort/solution.rs new file mode 100644 index 0000000..d7f431c --- /dev/null +++ b/challenges/sorting-algorithms/solutions/rust/insertion-sort/solution.rs @@ -0,0 +1,25 @@ +use std::io::{self, BufRead}; + +fn main() { + let mut numbers: Vec = Vec::new(); + let stdin = io::stdin(); + for line in stdin.lock().lines().skip(1) { + let line = line.unwrap(); + let number: i64 = line.trim().parse().unwrap(); + numbers.push(number); + } + insertion_sort(&mut numbers); + for number in numbers { + println!("{}", number); + } +} + +pub fn insertion_sort(array: &mut [T]) { + for index in 1..array.len() { + let mut index2 = index; + while index2 > 0 && array[index2] < array[index2 - 1] { + array.swap(index2, index2 - 1); + index2 -= 1; + } + } +}