Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in an array.
DSA C
void swap(int *a, int *b) {
int temp = *a;
*a = [1];
*b = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning temp to *a instead of *b.
Using variable names without dereferencing pointers.
✗ Incorrect
The swap function exchanges the values pointed by a and b. We assign *a = *b to copy the value from b to a.
2fill in blank
mediumComplete the Lomuto partition function to return the correct pivot index.
DSA C
int lomuto_partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] [1] pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '>' which moves larger elements incorrectly.
Using '<=' which includes equal elements on the left side.
✗ Incorrect
In Lomuto partition, elements less than the pivot are moved to the left. So the condition is arr[j] < pivot.
3fill in blank
hardFix the errors in the Hoare partition loop conditions to avoid infinite loops.
DSA C
int hoare_partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low - 1;
int j = high + 1;
while (1) {
do {
i++;
} while (arr[i] [1] pivot);
do {
j--;
} while (arr[j] [2] pivot);
if (i >= j)
return j;
swap(&arr[i], &arr[j]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= or >= causes pointers to move incorrectly and may cause infinite loops.
Using the same condition for both i and j loops.
✗ Incorrect
In Hoare partition, the left pointer moves right while arr[i] < pivot, and the right pointer moves left while arr[j] > pivot.
4fill in blank
hardFill both blanks to complete the Lomuto partition swap and return statement correctly.
DSA C
int lomuto_partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[[1]], &arr[[2]]);
return i + 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with wrong indices like low or i instead of i+1 and high.
Returning wrong pivot index.
✗ Incorrect
After the loop, swap arr[i+1] with arr[high] to place the pivot correctly.
5fill in blank
hardFill all three blanks to complete the Hoare partition inner loops and swap correctly.
DSA C
int hoare_partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low - 1;
int j = high + 1;
while (1) {
do {
i++;
} while (arr[i] [1] pivot);
do {
j--;
} while (arr[j] [2] pivot);
if (i >= j)
return j;
swap(&arr[[3]], &arr[j]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators causing infinite loops.
Swapping wrong indices.
✗ Incorrect
The left pointer moves while arr[i] < pivot, the right pointer moves while arr[j] > pivot, and swap uses arr[i] and arr[j].
