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[i]; arr[i] = arr[[1]]; arr[[1]] = temp;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with the wrong index like j or i itself.
Not using a temporary variable for swapping.
✗ Incorrect
We swap the element at position i with the element at position minIndex to place the smallest element at the correct position.
2fill in blank
mediumComplete the code to find the index of the smallest element in the unsorted part of the array.
DSA Javascript
for (let j = i + 1; j < arr.length; j++) { if (arr[j] [1] arr[minIndex]) { minIndex = j; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' which finds the largest element.
Using equality or inequality operators which do not help find the smallest.
✗ Incorrect
We look for the smallest element, so we check if arr[j] is less than arr[minIndex].
3fill in blank
hardFix the error in the loop that iterates over the array for selection sort.
DSA Javascript
for (let i = 0; i [1] arr.length - 1; i++) { // selection sort logic }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes an extra iteration leading to out-of-bounds errors.
Using '>' or '>=' causes the loop to never run or run incorrectly.
✗ Incorrect
We loop until i is less than arr.length - 1 because the last element will already be sorted.
4fill in blank
hardFill both blanks to complete the selection sort inner loop and update the smallest element index.
DSA Javascript
for (let j = [1]; j < arr.length; j++) { if (arr[j] [2] arr[minIndex]) { minIndex = j; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from i instead of i + 1 includes the already sorted part.
Using '>' instead of '<' finds the largest element.
✗ Incorrect
The inner loop starts from i + 1 to check the unsorted part, and we use '<' to find the smallest element.
5fill in blank
hardFill the blanks to create a dictionary mapping elements to their original positions before sorting.
DSA Javascript
let positions = {};
for (let i = 0; i < arr.length; i++) {
positions[[1]] = [2];
}
// After sorting, positions hold the index of each element
arr.sort((a, b) => a - b);
console.log(positions); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.length or i + 1 as keys or values incorrectly.
Mixing keys and values in the dictionary.
✗ Incorrect
We use arr[i] as the key and i as the value to map elements to their original positions. arr.length is unrelated here but included as distractor.