Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the array is sorted in non-decreasing order after sorting.
DSA Java
for (int i = 1; i < arr.length; i++) { if (arr[i].key < arr[i - 1].key) { return [1]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true inside the loop instead of false.
Returning 0 or null which are not boolean values.
✗ Incorrect
If any element is smaller than the previous one, the array is not sorted correctly, so return false.
2fill in blank
mediumComplete the code to perform a stable insertion sort on an array of objects with keys.
DSA Java
for (int i = 1; i < arr.length; i++) { Object key = arr[i]; int j = i - 1; while (j >= 0 && arr[j].key > key.key) { arr[j + 1] = arr[j]; j--; } arr[j + [1]] = key; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using j or j - 1 which places the key in the wrong position.
Using 0 or 2 which are incorrect offsets.
✗ Incorrect
After shifting elements, the key should be placed at position j + 1 to maintain stability.
3fill in blank
hardFix the error in the merge step of merge sort to maintain stability.
DSA Java
while (i < n1 && j < n2) { if (L[i].key [1] R[j].key) { arr[k++] = L[i++]; } else { arr[k++] = R[j++]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using < which breaks stability by not preserving order of equal keys.
Using > or >= which reverses the order.
✗ Incorrect
Using <= ensures that when keys are equal, the element from the left array is chosen first, preserving stability.
4fill in blank
hardComplete the code to verify sorting stability using original positions (assume 'origPos' field).
DSA Java
for (int i = 1; i < arr.length; i++) { if (arr[i].key == arr[i-1].key && arr[i].[1] < arr[i-1].[1]) { return [2]; } } return true;
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'key' for the position check.
Returning 'true' on violation.
✗ Incorrect
For equal keys, original positions must not decrease to preserve stability; return false on violation.
5fill in blank
hardComplete the Comparator for stable sorting by key then origPos (assume int fields).
DSA Java
Comparator<Obj> comp = Comparator.comparingInt(o -> o.[1]) .[2](o -> o.[3]);
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping primary and secondary fields.
Using thenComparing instead of thenComparingInt for ints.
✗ Incorrect
Primary sort by key, then by origPos on ties ensures stability.
