Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA C++
void swap(int& a, int& b) {
int temp = a;
a = [1];
b = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning 'a' to itself instead of 'b'.
Using 'temp' incorrectly.
✗ Incorrect
We assign 'a' the value of 'b' to swap their values correctly.
2fill in blank
mediumComplete the code to choose the pivot element for partitioning.
DSA C++
int partition(int arr[], int low, int high) {
int pivot = arr[[1]];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing the wrong index for the pivot.
Using an index outside the array bounds.
✗ Incorrect
The pivot is chosen as the last element at index 'high' for partitioning.
3fill in blank
hardFix the error in the recursive quickSort call to sort the left partition.
DSA C++
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, [1]);
quickSort(arr, pi + 1, high);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Including the pivot index in the left partition.
Using the wrong boundary for recursion.
✗ Incorrect
The left partition ends at 'pi - 1' to exclude the pivot element.
4fill in blank
hardFill both blanks to complete the partition function's loop condition and swap call.
DSA C++
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j [1] high; j++) {
if (arr[j] [2] pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' in the loop condition causing out-of-bound errors.
Using '>' instead of '<=' in the if condition.
✗ Incorrect
The loop runs while j < high, and elements less than or equal to pivot are swapped.
5fill in blank
hardFill all three blanks to complete the quickSort function with correct recursive calls and base condition.
DSA C++
void quickSort(int arr[], int low, int high) {
if (low [1] high) {
int pi = partition(arr, low, high);
quickSort(arr, low, [2]);
quickSort(arr, [3], high);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators in the base condition.
Including the pivot index in recursive calls.
✗ Incorrect
The base condition is 'low < high', and recursive calls sort left and right partitions excluding the pivot.