From 83b973f577b60be02be2ba77e806b36f83ce2ba3 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Fri, 20 Nov 2020 08:19:59 -0500 Subject: [PATCH] Finish week 3 assignment --- src/main.rs | 12 +++++------- src/quick_sort.rs | 21 ++++++++++++++------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index c0772c4..1977633 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,22 +30,20 @@ fn c1a2() { println!("course 1 assignment 2: {:?}", inversions); } +#[allow(dead_code)] fn c1a3() { - // let mut vec = read_to_vector("data/course_1_assignment_3.txt").unwrap(); - let mut vec = vec![2, 20, 1, 15, 3, 11, 13, 6, 16, 10, 19, 5, 4, 9, 8, 14, 18, 17, 7, 12]; + let mut vec = read_to_vector("data/course_1_assignment_3.txt").unwrap(); let mut comp_acc: usize = 0; quick_sort(&mut vec, &mut comp_acc); - // println!("{:?}", vec); - println!("{:?}", comp_acc); - println!("{:?}", 3/2); + println!("course 1 assignment 3: {:?}", comp_acc); /* 1: 162085 2: 164123 - 3: ? + 3: 138382 */ } fn main() { - //c1a2(); + c1a2(); c1a3(); } diff --git a/src/quick_sort.rs b/src/quick_sort.rs index c5ffb9b..adc1453 100644 --- a/src/quick_sort.rs +++ b/src/quick_sort.rs @@ -1,8 +1,7 @@ use std::cmp::PartialOrd; -#[allow(dead_code)] -fn median_of_three( v: &[T]) -> usize { +fn median_of_three( v: &[T]) -> usize { if v.len() < 3 { return 0; } @@ -14,12 +13,20 @@ fn median_of_three( v: &[T]) -> usize { v.len() / 2 }; let right = v.len() - 1; - - /* TODO: finish here */ - return 0; + let mut values = vec![v[left], v[middle], v[right]]; + bubble_sort(&mut values); + let median = values[1]; + if median == v[left] { + return left; + } else if median == v[middle] { + return middle; + } else if median == v[right]{ + return right; + } else { + panic!("Did not find median in values!"); + } } -#[allow(dead_code)] fn bubble_sort( v: &mut [T]) -> () { let mut unsorted = true; if v.len() <= 1 { @@ -37,7 +44,7 @@ fn bubble_sort( v: &mut [T]) -> () { } -pub fn quick_sort( v: &mut [T], comp_acc: &mut usize) -> () { +pub fn quick_sort( v: &mut [T], comp_acc: &mut usize) -> () { if v.len() <= 1 { return; }