Skip to content

Commit

Permalink
refactor: Refactor quicksort implementation (#2)
Browse files Browse the repository at this point in the history
- [x] Allow repeat items
  • Loading branch information
Michael-Liendo authored Nov 12, 2023
1 parent b84fbf6 commit 58419c6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Name | Description
--- | ---
[Binary Search](./src/binary_search.rs) | Search algorithm used to find elements in sorted lists
[Selection Sort](./src/selection_sort.rs) | Search algorithms used to find element in unsorted lists
[Quick Sort](./src/quicksort.rs) | Sorting algorithm that uses the divide and conquer approach
[Find Max (Recursive)](./src/find_max_recursive.rs) | Finds the maximum value on a collection using a recursive approach
[Sum (Recursive)](./src/sum_recursive.rs) | Sums elements in a collection using a recursive approach
[Queue](./src/queue.rs) | A FIFO data structure
Expand Down
47 changes: 24 additions & 23 deletions src/quicksort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,22 @@ where
// This is the recursive case where we plan
// to minimize the size of the problem thus
// applying a D&C mindset
let pivot = coll_clone.get(0).unwrap();
let mut less_than_pivot: Vec<T> = quicksort(
&coll_clone
.clone()
.into_iter()
.filter(|i| *i < *pivot)
.collect::<Vec<T>>(),
);
let greather_than_pivot: Vec<T> = quicksort(
&coll_clone
.clone()
.into_iter()
.filter(|i| *i > *pivot)
.collect::<Vec<T>>(),
);

less_than_pivot.push(*pivot);

less_than_pivot
.iter()
.chain(greather_than_pivot.iter())
.copied()
.collect()
let pivot = coll_clone.first().unwrap();

let less_than_pivot: Vec<T> = quicksort(&coll.iter().filter(|i| *i < pivot).cloned().collect());
let equal_to_pivot: Vec<T> = coll.iter().filter(|i| *i == pivot).cloned().collect();
let mut greater_than_pivot: Vec<T> =
quicksort(&coll.iter().filter(|i| *i > pivot).cloned().collect());

// Start building the result with the elements less than the pivot
let mut result = less_than_pivot;

// Add the elements equal to the pivot to the result
result.extend(equal_to_pivot);
// Add the elements greater than the pivot to the result
result.append(&mut greater_than_pivot);

result
}

#[cfg(test)]
Expand All @@ -59,4 +52,12 @@ mod tests {

assert_eq!(result, vec![2, 4, 5, 6, 7, 8, 10]);
}

#[test]
fn sorts_a_collection_with_repeated_elements() {
let items = vec![8, 2, 4, 6, 5, 7, 10, 8];
let result = quicksort(&items);

assert_eq!(result, vec![2, 4, 5, 6, 7, 8, 8, 10]);
}
}

0 comments on commit 58419c6

Please sign in to comment.