0
0
DSA C++programming~20 mins

Insertion Sort Algorithm in DSA C++ - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Insertion Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Insertion Sort on a small array
What is the output of the following C++ code after performing insertion sort on the array?
DSA C++
int arr[] = {4, 3, 2, 1};
int n = 4;
for (int i = 1; i < n; i++) {
    int key = arr[i];
    int j = i - 1;
    while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
    }
    arr[j + 1] = key;
}
for (int i = 0; i < n; i++) {
    std::cout << arr[i] << " ";
}
A1 3 2 4
B4 3 2 1
C1 2 3 4
D2 3 4 1
Attempts:
2 left
💡 Hint
Insertion sort places each element in its correct position by shifting larger elements to the right.
🧠 Conceptual
intermediate
1:30remaining
Number of comparisons in insertion sort best case
What is the number of comparisons insertion sort makes in the best case when the input array is already sorted?
An - 1
Bn * (n - 1) / 2
Cn
Dn * log n
Attempts:
2 left
💡 Hint
In the best case, the inner loop does not shift any elements.
🔧 Debug
advanced
2:00remaining
Identify the bug in this insertion sort implementation
What error will this code produce when run?
DSA C++
int arr[] = {5, 2, 4, 6, 1, 3};
int n = 6;
for (int i = 1; i < n; i++) {
    int key = arr[i];
    int j = i - 1;
    while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
    }
    arr[j + 1] = key;
}
ANo error, sorts correctly
BRuntime error: array index out of bounds
CCompilation error: missing semicolon
DLogical error: array remains unsorted
Attempts:
2 left
💡 Hint
Check the loop boundary condition for i.
🚀 Application
advanced
2:00remaining
Insertion sort on a linked list
Which of the following statements about insertion sort on a singly linked list is true?
AIt can be implemented by rearranging node pointers without extra space
BIt cannot be used on linked lists because they are unordered
CIt requires shifting elements like in arrays, so it is inefficient
DIt requires converting the list to an array first
Attempts:
2 left
💡 Hint
Think about how nodes can be moved by changing pointers.
🧠 Conceptual
expert
2:30remaining
Time complexity of insertion sort on nearly sorted data
If an array of size n is nearly sorted with only k elements out of place, what is the expected time complexity of insertion sort?
AO(k * log n)
BO(n + k^2)
CO(n log n)
DO(n * k)
Attempts:
2 left
💡 Hint
Insertion sort shifts elements only when needed, so fewer misplaced elements reduce work.