Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA Javascript
let temp = arr[[1]]; arr[[1]] = arr[j]; arr[j] = temp;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index like 0 or arr.length causes incorrect swaps.
Swapping with the same index does nothing.
✗ Incorrect
We use 'i' as the index to swap with 'j' during the bubble sort pass.
2fill in blank
mediumComplete the code to compare adjacent elements for swapping.
DSA Javascript
if (arr[j] [1] arr[j + 1]) { // swap }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will sort in descending order, not ascending.
Using '===' will never swap.
✗ Incorrect
We swap if the current element is greater than the next to sort in ascending order.
3fill in blank
hardFix the error in the loop condition to avoid out-of-bound errors.
DSA Javascript
for (let j = 0; j < arr.length [1] 1; j++) { // compare and swap }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' causes index out of range errors.
Using '*' or '/' makes no sense here.
✗ Incorrect
We subtract 1 to avoid accessing arr[j + 1] beyond array length.
4fill in blank
hardFill both blanks to complete the outer loop and inner loop for bubble sort.
DSA Javascript
for (let i = 0; i [1] arr.length; i++) { for (let j = 0; j [2] arr.length - i - 1; j++) { // compare and swap } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes index out of range errors.
Using '>' or '>=' causes loops not to run.
✗ Incorrect
Both loops run with '<' to iterate correctly over indices.
5fill in blank
hardFill all three blanks to complete the bubble sort function.
DSA Javascript
function bubbleSort(arr) {
for (let i = 0; i [1] arr.length; i++) {
for (let j = 0; j [2] arr.length - i - 1; j++) {
if (arr[j] [3] arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' in loops causes index errors.
Using '<' in swap condition sorts descending.
Using '>=' or '<=' in swap condition causes no swaps.
✗ Incorrect
Outer and inner loops use '<' to iterate; swap if current element is greater than next.