0
0
DSA Goprogramming~20 mins

Insertion Sort Algorithm in DSA Go - 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 Go code that uses insertion sort on the array [4, 3, 2, 1]?
DSA Go
package main
import "fmt"
func insertionSort(arr []int) {
    for i := 1; i < len(arr); i++ {
        key := arr[i]
        j := i - 1
        for j >= 0 && arr[j] > key {
            arr[j+1] = arr[j]
            j--
        }
        arr[j+1] = key
    }
}
func main() {
    arr := []int{4, 3, 2, 1}
    insertionSort(arr)
    fmt.Println(arr)
}
A[1 3 2 4]
B[4 3 2 1]
C[1 2 3 4]
D[2 3 4 1]
Attempts:
2 left
💡 Hint
Insertion sort moves smaller elements to the front step by step.
Predict Output
intermediate
2:00remaining
Insertion Sort with duplicate elements
What will be the output after running insertion sort on the array [5, 3, 5, 2, 2]?
DSA Go
package main
import "fmt"
func insertionSort(arr []int) {
    for i := 1; i < len(arr); i++ {
        key := arr[i]
        j := i - 1
        for j >= 0 && arr[j] > key {
            arr[j+1] = arr[j]
            j--
        }
        arr[j+1] = key
    }
}
func main() {
    arr := []int{5, 3, 5, 2, 2}
    insertionSort(arr)
    fmt.Println(arr)
}
A[5 3 5 2 2]
B[3 2 2 5 5]
C[2 3 5 2 5]
D[2 2 3 5 5]
Attempts:
2 left
💡 Hint
Duplicates should be placed next to each other in sorted order.
🧠 Conceptual
advanced
1:00remaining
Time complexity of insertion sort in worst case
What is the time complexity of insertion sort in the worst case scenario?
AO(n^2)
BO(n log n)
CO(n)
DO(log n)
Attempts:
2 left
💡 Hint
Worst case happens when the array is sorted in reverse order.
🔧 Debug
advanced
2:00remaining
Identify the bug in this insertion sort code
What error will this Go code produce when running insertion sort?
DSA Go
package main
import "fmt"
func insertionSort(arr []int) {
    for i := 1; i < len(arr); i++ {
        key := arr[i]
        j := i
        for j >= 0 && arr[j] > key {
            arr[j+1] = arr[j]
            j--
        }
        arr[j+1] = key
    }
}
func main() {
    arr := []int{3, 1, 2}
    insertionSort(arr)
    fmt.Println(arr)
}
ARuntime panic: index out of range
B[1 2 3]
C[3 1 2]
DSyntax error: missing colon
Attempts:
2 left
💡 Hint
Check the initial value of j and array indexing inside the loop.
🚀 Application
expert
3:00remaining
Number of shifts in insertion sort for a given array
How many times will elements be shifted (moved) during insertion sort on the array [8, 4, 3, 7, 6]?
A4
B6
C5
D7
Attempts:
2 left
💡 Hint
Count each time an element is moved to the right during sorting.