feat(quicksort): basic algorithm implemented

This commit is contained in:
2024-11-16 19:23:05 +01:00
parent 2213d38728
commit fc48949ad9
3 changed files with 41 additions and 5 deletions

View File

@@ -8,7 +8,6 @@ pub fn longest_palindrome(value: &str) -> String {
break;
}
if let Some(slice) = value.get(i..(i + pal_size - 1)) {
// let reverted_slice = slice.chars().rev().collect::<String>();
// if string was mutable, we count use .reserve()
let reverted_slice = slice.chars().rev().collect::<String>();
if slice == reverted_slice {
@@ -21,3 +20,34 @@ pub fn longest_palindrome(value: &str) -> String {
lp
}
pub fn quick_sort<T>(list: Vec<T>) -> Vec<T>
where
T: PartialOrd + Copy,
{
if list.is_empty() {
return list;
}
let mut pivot_list = vec![list[0]];
let pivot = pivot_list[0];
// arrange
let mut left_list: Vec<T> = Vec::new();
let mut right_list: Vec<T> = Vec::new();
for index in 1..list.len() {
let element = list[index];
if element > pivot {
right_list.push(element);
} else if element < pivot {
left_list.push(element);
} else {
pivot_list.push(element);
}
}
left_list = quick_sort(left_list);
right_list = quick_sort(right_list);
left_list.append(&mut pivot_list);
left_list.append(&mut right_list);
left_list
}

View File

@@ -30,4 +30,10 @@ pub fn run_easy() {
let bubled_list = easy_difficulty::bubble_sort(list);
println!("The original list sorted is {:?}", bubled_list);
let long_list = vec![
5, 1, 8, 20, 4, 15, 6, 7, 1, 4, 23, 9, 23, 5, 7, 7, 8, 0, 12, 4, 56, 18, 47, 23,
];
let sorted_list = medium_difficulty::quick_sort(long_list);
println!("The sorted list is: {:?}", sorted_list);
}

View File

@@ -14,8 +14,8 @@
// mod controlflow;
// mod traits;
// mod str_types;
mod functions;
// mod exercises;
// mod functions;
mod exercises;
fn main() {
// helloworld::hello_world_module();
@@ -27,6 +27,6 @@ fn main() {
// controlflow::control_flow_module();
//traits::traits_exercise();
// str_types::str_types_module();
functions::functions_module();
// exercises::run_easy();
// functions::functions_module();
exercises::run_easy();
}