Implement merge sort in Python

I know, I want to do this in Rust, but prototyping in Python comes much
more natural to me. I have to work on my Rust skills!
master
Felix Martin 2020-11-13 14:48:47 -05:00
parent e9f114bc48
commit 79a7a05b21
4 changed files with 68 additions and 0 deletions

3
.gitignore vendored
View File

@ -10,3 +10,6 @@ Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
# Sublime
algos.sublime-project
algos.sublime-workspace

9
Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "algos"
version = "0.1.0"
authors = ["Felix Martin <mail@felixm.de>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

37
src/main.py Normal file
View File

@ -0,0 +1,37 @@
def merge(a, b):
"""Merges two sorted lists"""
i, j = 0, 0
r = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
r.append(a[i])
i += 1
else:
r.append(b[j])
j += 1
while i < len(a):
r.append(a[i])
i += 1
while j < len(b):
r.append(b[j])
j += 1
return r
def merge_sort(v):
length = len(v)
if length <= 1:
return v
half_length = length // 2
a = merge_sort(v[:half_length])
b = merge_sort(v[half_length:])
return merge(a, b)
if __name__ == "__main__":
print(merge_sort([42, 12, 3, 1, 5]))

19
src/main.rs Normal file
View File

@ -0,0 +1,19 @@
use std::vec::Vec;
use std::clone::Clone;
fn merge_sort<T: Clone>(v: Vec<T>) -> Vec<T> {
if v.len() <= 1 {
return v;
}
let sorted = v.to_vec();
return sorted;
}
fn main() {
println!("Hello, world!");
let l = vec![2,1,3];
let l = merge_sort(l);
println!("{:?}", l);
}