📖 Scenario: You are working on a program that needs to sort a list of numbers efficiently. Sorting helps organize data so it is easier to search and analyze, like arranging books by their titles on a shelf.
🎯 Goal: Build a Rust program that uses the merge sort algorithm to sort a list of numbers in ascending order. You will create the list, set up a helper function, implement the merge sort logic, and finally print the sorted list.
📋 What You'll Learn
Create a vector called numbers with the exact values: 38, 27, 43, 3, 9, 82, 10
Create a helper function called merge that merges two sorted slices into a new sorted vector
Create a recursive function called merge_sort that sorts the vector using the merge sort algorithm
Print the sorted vector after applying merge_sort
💡 Why This Matters
🌍 Real World
Sorting is used everywhere, like organizing contacts on your phone or arranging products by price in an online store.
💼 Career
Understanding merge sort helps in software development roles where efficient data processing and algorithm knowledge are important.
Progress0 / 4 steps
1
Create the initial vector
Create a vector called numbers with these exact values: 38, 27, 43, 3, 9, 82, 10
DSA Rust
Hint
Use let numbers = vec![38, 27, 43, 3, 9, 82, 10]; to create the vector.
2
Create the merge helper function
Create a function called merge that takes two sorted slices of i32 called left and right, and returns a new sorted Vec by merging them.
DSA Rust
Hint
The merge function compares elements from left and right slices and pushes the smaller one into result until all elements are merged.
3
Implement the merge_sort function
Create a recursive function called merge_sort that takes a vector of i32 called arr and returns a sorted Vec using the merge sort algorithm. Use the merge function to combine sorted halves.
DSA Rust
Hint
The merge_sort function splits the vector into halves recursively until size 1, then merges them back sorted.
4
Print the sorted vector
Call the merge_sort function with the numbers vector and print the sorted result using println!.
DSA Rust
Hint
Use let sorted_numbers = merge_sort(numbers); and then println!("{:?}", sorted_numbers); to print the sorted vector.
Practice
(1/5)
1. What is the main idea behind the Merge Sort Algorithm?
easy
A. Divide the list into halves, sort each half, then merge them
B. Sort the list by repeatedly swapping adjacent elements
C. Pick a pivot and partition the list around it
D. Insert elements one by one into a sorted list
Solution
Step 1: Understand the divide and conquer approach
Merge sort splits the list into smaller parts to make sorting easier.
Step 2: Merge sorted halves
After sorting each half, it merges them to form a fully sorted list.
Final Answer:
Divide the list into halves, sort each half, then merge them -> Option A
Quick Check:
Merge Sort = Divide, Sort halves, Merge [OK]
Hint: Remember: split, sort, then merge halves [OK]
Common Mistakes:
Confusing merge sort with bubble sort
Thinking merge sort sorts in place without merging
Mixing merge sort with quicksort partitioning
2. Which of the following is the correct Rust function signature for a merge sort function that sorts a vector of integers?
easy
A. fn merge_sort(arr: &Vec<i32>) -> Vec<i32>
B. fn merge_sort(arr: Vec<i32>) -> Vec<i32>
C. fn merge_sort(arr: &mut Vec<i32>)
D. fn merge_sort(arr: Vec<i32>)
Solution
Step 1: Understand ownership and mutability in Rust
To sort in place, the function needs a mutable reference to the vector.
Step 2: Check function signature options
fn merge_sort(arr: &mut Vec<i32>) takes a mutable reference, allowing in-place sorting without ownership transfer.
Final Answer:
fn merge_sort(arr: &mut Vec<i32>) -> Option C
Quick Check:
Mutable reference needed for in-place sort [OK]
Hint: Use &mut Vec for in-place sorting in Rust [OK]
Common Mistakes:
Using owned Vec without returning sorted vector
Using immutable reference when mutation is needed
Missing return type when function returns new vector
3. What will be the output of the following Rust code snippet using merge sort?
fn main() {
let mut arr = vec![4, 1, 3, 2];
merge_sort(&mut arr);
println!("{:?}", arr);
}
fn merge_sort(arr: &mut Vec<i32>) {
if arr.len() > 1 {
let mid = arr.len() / 2;
let mut left = arr[..mid].to_vec();
let mut right = arr[mid..].to_vec();
merge_sort(&mut left);
merge_sort(&mut right);
merge(arr, &left, &right);
}
}
fn merge(arr: &mut Vec<i32>, left: &Vec<i32>, right: &Vec<i32>) {
let mut i = 0;
let mut j = 0;
let mut k = 0;
while i < left.len() && j < right.len() {
if left[i] <= right[j] {
arr[k] = left[i];
i += 1;
} else {
arr[k] = right[j];
j += 1;
}
k += 1;
}
while i < left.len() {
arr[k] = left[i];
i += 1;
k += 1;
}
while j < right.len() {
arr[k] = right[j];
j += 1;
k += 1;
}
}
medium
A. [2, 1, 3, 4]
B. [1, 2, 3, 4]
C. [1, 3, 2, 4]
D. [4, 3, 2, 1]
Solution
Step 1: Trace the recursive splitting
The array [4,1,3,2] is split into [4,1] and [3,2], then further split until single elements.
Step 2: Merge sorted halves
Single elements are merged back in sorted order: [1,4] and [2,3], then merged to [1,2,3,4].
Final Answer:
[1, 2, 3, 4] -> Option B
Quick Check:
Merge sort output = sorted array ascending [OK]
Hint: Merge sort always outputs sorted ascending list [OK]
Common Mistakes:
Confusing merge order and output
Forgetting to copy back merged elements
Mixing up indices during merge
4. Identify the bug in this Rust merge sort implementation snippet:
fn merge_sort(arr: &mut Vec<i32>) {
if arr.len() > 1 {
let mid = arr.len() / 2;
let mut left = arr[..mid].to_vec();
let mut right = arr[mid..].to_vec();
merge_sort(&mut left);
merge_sort(&mut right);
merge(arr, &left, &right);
}
}
fn merge(arr: &mut Vec<i32>, left: &Vec<i32>, right: &Vec<i32>) {
let mut i = 0;
let mut j = 0;
let mut k = 0;
while i < left.len() && j < right.len() {
if left[i] < right[j] {
arr[k] = left[i];
i += 1;
} else {
arr[k] = right[j];
j += 1;
}
k += 1;
}
while i < left.len() {
arr[k] = left[i];
i += 1;
k += 1;
}
while j < right.len() {
arr[k] = right[j];
j += 1;
k += 1;
}
}
medium
A. The merge condition should use <= instead of < to maintain stability
B. The function should return a new vector instead of modifying in place
C. The mid index calculation is incorrect and causes panic
D. The merge function does not handle empty vectors
Solution
Step 1: Analyze the merge comparison condition
The condition uses < which can reorder equal elements, breaking stability.
Step 2: Correct the condition for stable sort
Using <= ensures equal elements keep their original order, preserving stability.
Final Answer:
The merge condition should use <= instead of < to maintain stability -> Option A
Quick Check:
Use <= in merge to keep stable order [OK]
Hint: Use <= in merge to keep equal elements stable [OK]
Common Mistakes:
Ignoring stability in merge condition
Thinking mid calculation causes error
Assuming merge must return new vector
5. Given a large vector of integers with many duplicate values, how can you modify the merge sort algorithm in Rust to efficiently sort and remove duplicates during the merge step?
hard
A. Sort normally then use a separate pass to remove duplicates after merge sort completes
B. Change merge sort to quicksort for better duplicate handling
C. Use a HashSet to store elements during merge and convert back to vector
D. Modify the merge function to skip adding duplicates when merging sorted halves
Solution
Step 1: Understand duplicate removal during merge
While merging, compare current elements and skip adding if equal to last added element.
Step 2: Implement skipping duplicates in merge
This avoids extra passes and keeps sorting efficient by removing duplicates on the fly.
Final Answer:
Modify the merge function to skip adding duplicates when merging sorted halves -> Option D
Quick Check:
Skip duplicates during merge for efficient unique sort [OK]
Hint: Skip duplicates while merging to avoid extra passes [OK]
Common Mistakes:
Removing duplicates only after full sort wastes time
Using HashSet breaks order and adds overhead
Switching to quicksort doesn't inherently remove duplicates
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.