📖 Scenario: You have a list of numbers that you want to arrange from smallest to largest, just like organizing books by height on a shelf.
🎯 Goal: Build a Rust program that sorts a list of numbers using the insertion sort method, which places each number in its correct spot one by one.
📋 What You'll Learn
Create a vector called numbers with the exact values: 8, 3, 5, 1, 9
Create a variable called n that stores the length of numbers
Use a for loop with variable i from 1 to n to perform insertion sort
Inside the loop, use a while loop with variable j to move elements and insert the current number
Print the sorted numbers vector at the end
💡 Why This Matters
🌍 Real World
Sorting is used in many places like organizing data, searching faster, and making lists easier to understand.
💼 Career
Understanding sorting algorithms like insertion sort helps in coding interviews and building efficient software.
Progress0 / 4 steps
1
Create the initial list of numbers
Create a vector called numbers with the exact values 8, 3, 5, 1, 9.
DSA Rust
Hint
Use let mut numbers = vec![8, 3, 5, 1, 9]; to create a mutable vector.
2
Create a variable for the length of the list
Create a variable called n that stores the length of the numbers vector.
DSA Rust
Hint
Use let n = numbers.len(); to get the length of the vector.
3
Implement the insertion sort algorithm
Use a for loop with variable i from 1 to n to perform insertion sort. Inside the loop, use a while loop with variable j to move elements and insert the current number.
DSA Rust
Hint
Use a for loop from 1 to n, and inside it a while loop to shift elements until the correct position is found.
4
Print the sorted list
Print the sorted numbers vector using println!.
DSA Rust
Hint
Use println!("{:?}", numbers); to print the vector in debug format.
Practice
(1/5)
1. What is the main idea behind the Insertion Sort algorithm?
easy
A. Divide the array into halves and sort each half recursively
B. Build the sorted array one element at a time by inserting elements in their correct position
C. Swap adjacent elements if they are in the wrong order repeatedly
D. Select the smallest element and swap it with the first unsorted element
Solution
Step 1: Understand insertion sort process
Insertion sort builds the sorted list by taking one element at a time and placing it in the correct position among the already sorted elements.
Step 2: Compare with other sorting methods
Unlike divide and conquer (merge sort) or swapping adjacent elements (bubble sort), insertion sort inserts elements directly into their correct place.
Final Answer:
Build the sorted array one element at a time by inserting elements in their correct position -> Option B
Quick Check:
Insertion sort = Insert elements correctly one by one [OK]
Hint: Insertion sort inserts elements into sorted part step-by-step [OK]
Common Mistakes:
Confusing insertion sort with bubble sort
Thinking it divides array like merge sort
Assuming it swaps only smallest elements
2. Which of the following Rust code snippets correctly starts the insertion sort outer loop?
easy
A. for i in 1..arr.len() {
B. for i in 0..arr.len() {
C. for i in (1..arr.len()).rev() {
D. for i in 0..arr.len()-1 {
Solution
Step 1: Identify insertion sort loop start
Insertion sort starts from the second element (index 1) because the first element is considered sorted.
Step 2: Check Rust range syntax
The range 1..arr.len() correctly iterates from index 1 to the last index (exclusive of arr.len()).
Final Answer:
for i in 1..arr.len() { -> Option A
Quick Check:
Start loop at 1 for insertion sort [OK]
Hint: Insertion sort outer loop starts at index 1 [OK]
Common Mistakes:
Starting loop at 0 instead of 1
Using reversed range incorrectly
Off-by-one errors in range
3. What will be the output of the following Rust code after running insertion sort on arr = [4, 3, 1, 5]?
let mut arr = vec![4, 3, 1, 5];
for i in 1..arr.len() {
let key = arr[i];
let mut j = i;
while j > 0 && arr[j - 1] > key {
arr[j] = arr[j - 1];
j -= 1;
}
arr[j] = key;
}
println!("{:?}", arr);
medium
A. [3, 4, 1, 5]
B. [4, 3, 1, 5]
C. [1, 3, 4, 5]
D. [1, 4, 3, 5]
Solution
Step 1: Trace first iteration (i=1)
key=3, compare with 4; 4 > 3 so shift 4 right, insert 3 at index 0. Array: [3,4,1,5]
Step 2: Trace second iteration (i=2)
key=1, compare with 4 and 3; both >1 so shift them right, insert 1 at index 0. Array: [1,3,4,5]
Step 3: Trace third iteration (i=3)
key=5, compare with 4; 4 < 5 so no shift, insert 5 at index 3. Array unchanged: [1,3,4,5]
4. Identify the bug in this Rust insertion sort snippet:
let mut arr = vec![2, 5, 3];
for i in 1..arr.len() {
let key = arr[i];
let mut j = i - 1;
while j >= 0 && arr[j] > key {
arr[j + 1] = arr[j];
j -= 1;
}
arr[j + 1] = key;
}
medium
A. The key is not assigned correctly
B. The array is not mutable
C. The for loop range is incorrect
D. The variable j is unsigned and j >= 0 check causes infinite loop
Solution
Step 1: Analyze variable j type and condition
In Rust, usize is unsigned, so j >= 0 is always true, causing infinite loop when j underflows.
Step 2: Understand while loop behavior
When j reaches 0 and decrements, it wraps to a large number, so loop never ends.
Final Answer:
The variable j is unsigned and j >= 0 check causes infinite loop -> Option D
Quick Check:
Unsigned j with j >= 0 causes infinite loop [OK]
Hint: Unsigned index can't be checked with j >= 0 safely [OK]
Common Mistakes:
Ignoring unsigned integer wrap-around
Assuming j can be negative
Not using a different loop condition
5. You want to modify insertion sort in Rust to sort a vector of tuples Vec<(i32, String)> by the integer value. Which change is needed in the comparison inside the while loop?
hard
A. Change arr[j - 1] > key to arr[j - 1].0 > key.0
B. Change arr[j - 1] > key to arr[j - 1].1 > key.1
C. No change needed, tuples compare automatically by second element
D. Change arr[j - 1] > key to arr[j - 1].1.len() > key.1.len()
Solution
Step 1: Understand tuple sorting by first element
To sort by the integer part of the tuple, compare the first element (.0) of each tuple.
Step 2: Modify comparison in while loop
Replace arr[j - 1] > key with arr[j - 1].0 > key.0 to compare integers correctly.
Final Answer:
Change arr[j - 1] > key to arr[j - 1].0 > key.0 -> Option A
Quick Check:
Compare tuple first elements for sorting [OK]
Hint: Compare tuple.0 to sort by integer part [OK]
Common Mistakes:
Comparing string part instead of integer
Assuming tuples compare by second element automatically
Using length of string for comparison
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.