From c502c17e7c2920e43fe9598cf89277492a9e353e Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 8 Mar 2022 10:02:48 +0100 Subject: [PATCH] feat(solutions): add `sorting-algorithms/rust/insertion-sort` --- .../solutions/rust/insertion-sort/README.md | 3 +++ .../solutions/rust/insertion-sort/solution.rs | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 challenges/sorting-algorithms/solutions/rust/insertion-sort/README.md create mode 100644 challenges/sorting-algorithms/solutions/rust/insertion-sort/solution.rs 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; + } + } +}