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;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning 'a' to 'temp' again instead of 'b'.
Using '0' instead of 'b'.
✗ Incorrect
To swap two variables, assign 'a' the value of 'b', then 'b' the original value of 'a' stored in 'temp'.
2fill in blank
mediumComplete the code to choose the pivot element as the last element of the array segment.
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;
}Attempts:
3 left
💡 Hint
Common Mistakes
Choosing 'low' as pivot index instead of 'high'.
Using an index outside the segment.
✗ Incorrect
The pivot is chosen as the last element in the current segment, which is at index 'high'.
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);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pi' instead of 'pi - 1' causing infinite recursion.
Using 'high' which sorts the whole array again.
✗ Incorrect
The left partition ends at 'pi - 1' because 'pi' is the pivot's final position.
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] < pivot) {
i++;
swap(arr[i], arr[[2]]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' in loop causing out-of-bound errors.
Swapping with 'i' instead of 'j' inside the loop.
✗ Incorrect
The loop runs while 'j' is less than 'high' and swaps elements at 'i' and 'j'.
5fill in blank
hardFill all three blanks to complete the quickSort function's 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);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' in base condition causing infinite recursion.
Using 'pi' instead of 'pi - 1' or 'pi + 1' in recursive calls.
✗ Incorrect
The base condition is 'low < high'. The left recursive call sorts up to 'pi - 1', and the right starts from 'pi + 1'.
