Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

modified the function to take slices as input and return a vector without the need to create and manipulate additional Vec instances. #59

Merged
merged 1 commit into from
Jul 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 19 additions & 19 deletions src/sorting/merge_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,32 @@ pub fn merge_sort<T: Ord + Copy>(array: &[T]) -> Vec<T> {
if array.len() < 2 {
return array.to_vec();
}
// Get the middle element of the array.
let middle = array.len() / 2;
// Divide the array into left and right halves.
let mut left = merge_sort(&array[..middle]);
let mut right = merge_sort(&array[middle..]);
// Call merge function using parameters as both left array and right array.
merge(&mut left, &mut right)
let left = merge_sort(&array[..middle]);
let right = merge_sort(&array[middle..]);
merge(&left, &right)
}

fn merge<T: Ord + Copy>(left: &mut Vec<T>, right: &mut Vec<T>) -> Vec<T> {
let mut result = Vec::new();

for _ in 0..left.len() + right.len() {
if left.is_empty() {
result.append(right);
break;
} else if right.is_empty() {
result.append(left);
break;
} else if left[0] <= right[0] {
result.push(left.remove(0));
fn merge<T: Ord + Copy>(left: &[T], right: &[T]) -> Vec<T> {
let mut result = Vec::with_capacity(left.len() + right.len());
let mut left_iter = left.iter();
let mut right_iter = right.iter();

let mut left_next = left_iter.next();
let mut right_next = right_iter.next();

while let (Some(left_val), Some(right_val)) = (left_next, right_next) {
if left_val <= right_val {
result.push(*left_val);
left_next = left_iter.next();
} else {
result.push(right.remove(0));
result.push(*right_val);
right_next = right_iter.next();
}
}

result.extend(left_next);
result.extend(right_next);
result
}

Expand Down
Loading