Skip to content

Instantly share code, notes, and snippets.

@Mroik
Last active September 10, 2022 13:09
Show Gist options
  • Save Mroik/dedbde000e60d517ae3db076aa0815fe to your computer and use it in GitHub Desktop.
Save Mroik/dedbde000e60d517ae3db076aa0815fe to your computer and use it in GitHub Desktop.
use rand::Rng;
use std::cmp::Ordering;
fn main() {
let mut list: [i32; 1000] = [0; 1000];
let mut helper: [i32; 1000] = [0; 1000];
let mut rng = rand::thread_rng();
for x in 0..1000 {
list[x] = rng.gen_range(0..999);
}
for x in 0..1000 {
println!("{}", list[x]);
}
println!("STOP");
mergesort(&mut list, &mut helper, 0, 1000);
for x in 0..1000 {
println!("{}", list[x]);
}
}
fn mergesort(list: &mut [i32; 1000], temp: &mut [i32; 1000], start: usize, end: usize) {
if end - start <= 1 {
return;
}
let mid = (end - start) / 2 + start;
mergesort(list, temp, start, mid);
mergesort(list, temp, mid, end);
let mut l = start;
let mut r = mid;
for x in start..end {
if r >= end {
temp[x] = list[l];
l += 1;
} else if l >= mid {
temp[x] = list[r];
r += 1;
} else {
match list[l].cmp(&list[r]) {
Ordering::Less => {
temp[x] = list[l];
l += 1;
},
Ordering::Greater => {
temp[x] = list[r];
r += 1;
},
Ordering::Equal => {
temp[x] = list[l];
l += 1;
},
}
}
}
for x in start..end {
list[x] = temp[x];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment