Task 2 — Sorted Element Insertion
Objective
Create a function that inserts an integer into an already sorted slice while preserving ascending order.
The element must be placed directly into its correct sorted position.
Input
The initial sorted slice is:
list := []int{
1, 2, 5, 7, 8, 11, 14,
}
The function receives an integer value that should be inserted into the slice.
Function
The function is named:
AddElement(...)
Conceptually, it receives:
AddElement(list, value)
and produces a sorted slice containing the new value.
Requirements
The function must:
- receive an already sorted
[]int - receive an integer value
- determine the correct position for the new value
- insert the value at that position
- preserve ascending order
The resulting slice must contain all original elements and the newly inserted element.
Case 1
Call:
AddElement(list, 4)
The value 4 belongs between:
2 and 5
Expected Result
[]int{
1, 2, 4, 5, 7, 8, 11, 14,
}
Case 2
Call:
AddElement(list, 9)
The value 9 belongs between:
8 and 11
Expected Result
[]int{
1, 2, 5, 7, 8, 9, 11, 14,
}
Case 3
Call:
AddElement(list, 12)
The value 12 belongs between:
11 and 14
Expected Result
[]int{
1, 2, 5, 7, 8, 11, 12, 14,
}
Boundary Cases
A general implementation should also support values that belong at the beginning or end of the slice.
For example:
AddElement(list, 0)
should place 0 before the current first element.
Similarly:
AddElement(list, 20)
should place 20 after the current last element.
Duplicate Values
The original task does not specify whether duplicate values are allowed.
Therefore, duplicate handling is intentionally left as an implementation decision unless additional requirements are introduced.
Implementation Notes
The input slice is already sorted.
The objective is therefore to determine the correct insertion position rather than treating the task as a general unsorted-list sorting problem.
The implementation should work with other sorted integer slices and insertion values.