Array
Insertion
At End
In the same array (fixed size)
- Check if array has capacity
- If yes, add the element to the array's length + 1
function insertSorted(arr, n, key, capacity){
if (n >= capacity) return n;
arr[n] = key;
return (n + 1);
}
Copy to a new array (dynamically sized)
arr.push(new_element)
def insertAtEnd():
arr.append(new_element)
Searching
Binary Search
Here's the code using Search Algorithms#Binary Search algorithm for searching an array:
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}