Skip to content

Instantly share code, notes, and snippets.

@mizukmb
Created May 11, 2020 15:07
Show Gist options
  • Save mizukmb/9b8de2fe3e86fd8f026abb5c20c31070 to your computer and use it in GitHub Desktop.
Save mizukmb/9b8de2fe3e86fd8f026abb5c20c31070 to your computer and use it in GitHub Desktop.
バブルソート、選択ソート、挿入ソート、マージソート
fn bubble_sort(values: &Vec<i32>) -> Vec<i32> {
let mut result = values.clone();
for i in 0..(values.len() - 2) {
for base in 0..(values.len() - i) {
let target_index = base + 1;
if target_index >= values.len() {
break;
}
if result[base] > result[target_index] {
result = swap(result, base, target_index);
}
}
}
result
}
fn selection_sort(values: &Vec<i32>) -> Vec<i32> {
let mut result = values.clone();
for i in 0..(result.len() - 1) {
let mut min = i;
for j in (i + 1)..result.len() {
if result[j] < result[min] {
min = j;
}
}
result = swap(result, i, min);
}
result
}
fn insertion_sort(values: &Vec<i32>) -> Vec<i32> {
let mut result = values.clone();
if result[0] > result[1] {
result = swap(result, 0, 1);
}
for i in 1..(result.len() - 1) {
if result[i] > result[i + 1] {
let mut base = i + 1;
let mut target_index = i;
loop {
result = swap(result, base, target_index);
if target_index as i32 - 1 < 0 || result[base - 1] > result[target_index - 1] {
break;
}
base -= 1;
target_index -= 1;
}
}
}
result
}
fn merge_sort(values: &Vec<i32>) -> Vec<i32> {
values.chunks(2).fold(vec![0; 0], |mut acc, x| {
acc.append(&mut x.to_vec());
insertion_sort(&acc)
})
}
fn swap(values: Vec<i32>, from: usize, to: usize) -> Vec<i32> {
let mut result = values.clone();
let tmp = result[from];
result[from] = result[to];
result[to] = tmp;
result
}
fn display(values: &Vec<i32>) {
println!("{:?}", values);
}
fn main() {
let values = vec![4, 3, 100, 40, 1, 7, 5];
println!("Bubble Sort");
display(&values);
let r = bubble_sort(&values);
display(&r);
println!("");
println!("Selection Sort");
display(&values);
let r = selection_sort(&values);
display(&r);
println!("");
println!("Insertion Sort");
display(&values);
let r = insertion_sort(&values);
display(&r);
println!("");
println!("Merge Sort");
display(&values);
let r = merge_sort(&values);
display(&r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment