From 3dd4bb0173a6a4710faf7580a6903020424349cd Mon Sep 17 00:00:00 2001 From: Akshat Adsule <30205531+AkshatAdsule@users.noreply.github.com> Date: Thu, 29 Jul 2021 13:36:30 -0700 Subject: [PATCH] Add merge sort algorithm --- algorithms/Rust/sorting/merge-sort/Cargo.toml | 10 +++ .../Rust/sorting/merge-sort/src/main.rs | 66 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 algorithms/Rust/sorting/merge-sort/Cargo.toml create mode 100644 algorithms/Rust/sorting/merge-sort/src/main.rs diff --git a/algorithms/Rust/sorting/merge-sort/Cargo.toml b/algorithms/Rust/sorting/merge-sort/Cargo.toml new file mode 100644 index 00000000..1b974307 --- /dev/null +++ b/algorithms/Rust/sorting/merge-sort/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "merge-sort" +version = "0.1.0" +authors = ["Akshat Adsule <30205531+AkshatAdsule@users.noreply.github.com>"] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.8.3" \ No newline at end of file diff --git a/algorithms/Rust/sorting/merge-sort/src/main.rs b/algorithms/Rust/sorting/merge-sort/src/main.rs new file mode 100644 index 00000000..6f8b8926 --- /dev/null +++ b/algorithms/Rust/sorting/merge-sort/src/main.rs @@ -0,0 +1,66 @@ +use rand::{distributions::Uniform, Rng}; + +fn main() { + // Create random numbers + let range = Uniform::from(0..=100); + let values: Vec = rand::thread_rng().sample_iter(&range).take(100).collect(); + println!("Sorting: {:?}",values); + let result = merge_sort(values); + println!("Sorted: {:?}", result); +} + +// Limit type to only objects that can be ordered, cloned and copied +fn merge_sort(nums: Vec) -> Vec { + // If array only has one item, it is already sorted :-) + if nums.len() == 1 { + return vec![nums[0]]; + } + + // If array has 2 items, just compare the values and sort + if nums.len() == 2 { + if nums[0] <= nums[1] { + return vec![nums[0], nums[1]]; + } else { + return vec![nums[1], nums[0]]; + } + } + + // Split into 2 + let half = nums.len() / 2; + let mut left = merge_sort((&nums[0..half]).to_vec()); + let mut right = merge_sort((&nums[half..]).to_vec()); + + let mut sorted: Vec = Vec::new(); + + loop { + // If either array is empty, the values in the other array must be larger + // and so we should dump the remaining array's content into the sorted array + if left.is_empty() { + for i in right { + sorted.push(i); + } + break; + } + if right.is_empty() { + for i in left { + sorted.push(i); + } + break; + } + + // Merge arrays + if left[0] >= right[0] { + sorted.push(right[0]); + right.remove(0); + continue; + } + if left[0] <= right[0] { + sorted.push(left[0]); + left.remove(0); + continue; + } + } + + // return sorted array + sorted +}