Complete the code to swap two elements in the array.
fn swap(arr: &mut [i32], i: usize, j: usize) {
let temp = arr[[1]];
arr[i] = arr[j];
arr[j] = temp;
}We store the element at index i in temp before swapping.
Complete the code to choose the pivot element as the last element of the array slice.
fn partition(arr: &mut [i32]) -> usize {
let pivot = arr[[1]];
let mut i = 0;
for j in 0..arr.len() - 1 {
if arr[j] <= pivot {
arr.swap(i, j);
i += 1;
}
}
arr.swap(i, arr.len() - 1);
i
}The pivot is chosen as the last element, so its index is arr.len() - 1.
Fix the error in the recursive quicksort call to sort the left partition correctly.
fn quicksort(arr: &mut [i32]) {
if arr.len() > 1 {
let pivot_index = partition(arr);
quicksort(&mut arr[0..[1]]);
quicksort(&mut arr[pivot_index + 1..arr.len()]);
}
}The left partition is from start to pivot_index (exclusive), so use 0..pivot_index.
Fill both blanks to correctly partition the array and return the pivot index.
fn partition(arr: &mut [i32]) -> usize {
let pivot = arr[[1]];
let mut i = 0;
for j in 0..arr.len() - 1 {
if arr[j] [2] pivot {
arr.swap(i, j);
i += 1;
}
}
arr.swap(i, arr.len() - 1);
i
}The pivot is the last element, so index is arr.len() - 1. We compare elements less than or equal to pivot using <=.
Fill all three blanks to complete the quicksort function with correct recursive calls and base case.
fn quicksort(arr: &mut [i32]) {
if arr.len() [1] 1 {
let pivot_index = partition(arr);
quicksort(&mut arr[0..[2]]);
quicksort(&mut arr[[3]..arr.len()]);
}
}The base case is when length is greater than 1. The left slice ends at pivot_index, and the right slice starts at pivot_index + 1.
