chore(Rust): add merge sort (#403)

* Add merge sort algorithm

* add rust files to gitignore

* Revert "add rust files to gitignore"

This reverts commit d6a1ab819b.

* Move gitignore to cargo project

* create readme for merge sort

* add merge sort
pull/407/head
Akshat Adsule 2021-07-30 19:17:13 -07:00 committed by GitHub
parent dcdf04876b
commit cdd7b26e5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 97 additions and 1 deletions

View File

@ -1,4 +1,5 @@
# Rust
1. [Palindrome Check](strings/palindrome/README.md)
1. [Palindrome Check](strings/palindrome/README.md)
2. [Merge Sort](sorting/merge-sort/README.md)

View File

@ -0,0 +1,4 @@
### Rust
Cargo.lock
# Rust compiled output
target

View File

@ -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"

View File

@ -0,0 +1,15 @@
This sorts an array using Merge Sort. The sort is generic and will work with with any `Vec` whose items have the `std::cmp::Ord ` and `Copy` traits. More information about Merge Sort can be found [here](https://en.wikipedia.org/wiki/Merge_sort)
## Prerequisites
- Rust (https://rust-lang.org)
## Instructions for running the project
- Open a terminal/powershell window in the folder/directory.
- Run the following command
```bash
cargo run --release
```

View File

@ -0,0 +1,66 @@
use rand::{distributions::Uniform, Rng};
fn main() {
// Create random numbers
let range = Uniform::from(0..=100);
let values: Vec<i32> = 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<T: std::cmp::Ord + Copy>(nums: Vec<T>) -> Vec<T> {
// 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<T> = 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
}