function binarySearch(array, target) {
let left = 0;
let right = array.length - 1;
while (left <= right) {
let middle = Math.floor((left + right) / 2);
if (array[middle] === target) {
return middle;
} else if (array[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
let sortedArray = [10, 20, 30, 40, 50];
console.log(binarySearch(sortedArray, 30)); // Output: 2
console.log(binarySearch(sortedArray, 60)); // Output: -1
Sorting algorithms arrange the elements of a data structure in a specific order. A common example is the bubble sort algorithm.