![]() |
VOOZH | about |
In a sorted array, the search operation can be performed by using binary search.
π Search Operation in a sorted array
Below is the implementation of the above approach:
Index: 5
Time Complexity: O(log(n)) Using Binary Search
Auxiliary Space: O(log(n)) due to recursive calls, otherwise iterative version uses Auxiliary Space of O(1).
In a sorted array, a search operation is performed for the possible position of the given element by using Binary search, and then an insert operation is performed followed by shifting the elements. And in an unsorted array, the insert operation is faster as compared to the sorted array because we donβt have to care about the position at which the element is placed.
π Insert Operation in sorted array
Below is the implementation of the above approach:
Before Insertion: 12 16 20 40 50 70 After Insertion: 12 16 20 26 40 50 70
Time Complexity: O(N) [In the worst case all elements may have to be moved]
Auxiliary Space: O(1)
In the delete operation, the element to be deleted is searched using binary search, and then the delete operation is performed followed by shifting the elements.
Below is the implementation of the above approach:
Array before deletion 10 20 30 40 50 Array after deletion 10 20 40 50
Time Complexity: O(N). In the worst case all elements may have to be moved
Auxiliary Space: O(log N). An implicit stack will be used