Compare commits
3 commits
9f847fe038
...
c370cc4486
Author | SHA1 | Date | |
---|---|---|---|
c370cc4486 | |||
b607608b85 | |||
15d253d49c |
10
CHANGELOG.md
10
CHANGELOG.md
|
@ -1,3 +1,13 @@
|
|||
<a name="v0.4.0"></a>
|
||||
## v0.4.0 (2017-08-27)
|
||||
|
||||
|
||||
#### Features
|
||||
|
||||
* add quicksort ([b607608b](b607608b))
|
||||
|
||||
|
||||
|
||||
<a name="v0.3.0"></a>
|
||||
## v0.3.0 (2017-08-27)
|
||||
|
||||
|
|
|
@ -18,7 +18,6 @@ impl Algorithm for Insertionsort {
|
|||
}
|
||||
vector[i] = smallest_value;
|
||||
}
|
||||
println!("{:?}", vector);
|
||||
}
|
||||
return Ok(vector);
|
||||
}
|
||||
|
|
|
@ -6,3 +6,4 @@ pub trait Algorithm {
|
|||
pub mod bubblesort;
|
||||
pub mod mergesort;
|
||||
pub mod insertionsort;
|
||||
pub mod quicksort;
|
||||
|
|
59
src/algorithms/quicksort.rs
Normal file
59
src/algorithms/quicksort.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
use algorithms::Algorithm;
|
||||
|
||||
pub struct Quicksort;
|
||||
|
||||
impl Algorithm for Quicksort {
|
||||
fn sort(mut vector: Vec<i32>) -> Result<Vec<i32>, &'static str> {
|
||||
let pivot = match vector.pop() {
|
||||
Some(v) => v,
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
let mut pivots: Vec<i32> = Vec::new();
|
||||
pivots.push(pivot);
|
||||
|
||||
let mut smaller: Vec<i32> = Vec::new();
|
||||
let mut larger: Vec<i32> = Vec::new();
|
||||
|
||||
while vector.len() != 0 {
|
||||
let element = match vector.pop() {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
return Err(
|
||||
"Vector had a length not equal to 0, but still had no more element in it. This point should not be reachable.",
|
||||
)
|
||||
}
|
||||
};
|
||||
if element < pivot {
|
||||
smaller.push(element);
|
||||
} else if element > pivot {
|
||||
larger.push(element);
|
||||
} else {
|
||||
pivots.push(element);
|
||||
}
|
||||
}
|
||||
|
||||
let mut result: Vec<i32> = Vec::new();
|
||||
|
||||
for v in match Quicksort::sort(smaller) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
{
|
||||
result.push(v);
|
||||
}
|
||||
|
||||
for v in pivots {
|
||||
result.push(v);
|
||||
}
|
||||
|
||||
for v in match Quicksort::sort(larger) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
{
|
||||
result.push(v);
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
|
@ -1,11 +1,11 @@
|
|||
mod algorithms;
|
||||
|
||||
use algorithms::insertionsort::Insertionsort;
|
||||
use algorithms::quicksort::Quicksort;
|
||||
use algorithms::Algorithm;
|
||||
|
||||
fn main() {
|
||||
let unsorted: Vec<i32> = vec![2498, 29687, 24, 5, 94545, 8, 51, 152, 48, 871, 5];
|
||||
let sorted = match Insertionsort::sort(unsorted) {
|
||||
let sorted = match Quicksort::sort(unsorted) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
println!("Something went wrong! {}", e);
|
||||
|
|
Loading…
Reference in a new issue