Challenge - 5 Problems
Insertion Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Insertion Sort on a small array
What is the output of the following Rust code after sorting the array using insertion sort?
DSA Rust
fn insertion_sort(arr: &mut [i32]) {
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;
}
}
fn main() {
let mut data = [5, 2, 9, 1, 5];
insertion_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Insertion sort places each element in its correct position by shifting larger elements to the right.
✗ Incorrect
Insertion sort iterates through the array, inserting each element into the sorted portion on the left. The final sorted array is [1, 2, 5, 5, 9].
🧠 Conceptual
intermediateNumber of comparisons in insertion sort
For an array of size 5 sorted in descending order, how many comparisons does insertion sort perform in the worst case?
Attempts:
2 left
💡 Hint
Worst case is when each new element is smaller than all sorted elements.
✗ Incorrect
Insertion sort compares each element with all previously sorted elements in the worst case. For size 5, comparisons = 1+2+3+4 = 10.
🔧 Debug
advancedIdentify the bug in this insertion sort implementation
What error will this Rust code produce when run?
DSA Rust
fn insertion_sort(arr: &mut [i32]) {
for i in 1..arr.len() {
let key = arr[i];
let mut j = i + 1;
while j > 0 && arr[j] > key {
arr[j] = arr[j - 1];
j -= 1;
}
arr[j] = key;
}
}
fn main() {
let mut data = [3, 1, 4];
insertion_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Check the condition inside the while loop carefully.
✗ Incorrect
The condition arr[j] > key accesses arr[j] when j can be equal to arr.len(), causing out of bounds panic.
📝 Syntax
advancedWhich option will cause a syntax error in Rust?
Which of the following insertion sort code snippets will cause a syntax error?
Attempts:
2 left
💡 Hint
Look for missing semicolons in Rust code.
✗ Incorrect
Option A is missing a semicolon after arr[j] = arr[j - 1], causing a syntax error.
🚀 Application
expertInsertion sort on linked list output
Given a singly linked list with values 4 -> 3 -> 1 -> 2 -> null, what is the state of the list after applying insertion sort?
Attempts:
2 left
💡 Hint
Insertion sort on linked list rearranges nodes to ascending order.
✗ Incorrect
Insertion sort on linked list sorts nodes by inserting each node into the sorted part. Final sorted list is 1 -> 2 -> 3 -> 4 -> null.
