Linear Search:
function search(arr, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === value) return i
}
return -1
}
console.log(search([2, 11, 23, 44, 9], 23))
Answer: 2
😊😊😊😊😊😊😊😊
Binary Search:
function binary(arr, value) {
let start = 0
let end = arr.length - 1
while (start <= end) {
let middle = Math.round((start + end) / 2)
if (arr[middle] === value) return middle
if (value > arr[middle]) {
start = middle + 1
}
else if (value < arr[middle]) {
end = middle - 1
}
}
return -1
}
console.log(binary([2, 3, 5, 8, 11, 44, 76, 88], 44))
Answer: 5
😊😊😊😊😊😊😊😊
Bubble Sort: O(n2)
function bubble(arr) {
let isSwap;
for (let i = 0; i < arr.length; i++) {
isSwap = false
for (let j = 0; j < arr.length - i - 1; j++) {
console.log(arr[i], arr[j])
if (arr[j] > arr[j + 1]) {
let temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
isSwap = true
}
}
if (!isSwap) break
}
return arr
}
console.log(bubble([2, 1, 4, -22, 55, -1])) //[ -22, -1, 1, 2, 4, 55 ]
😊😊😊😊😊😊😊😊
SelectionSort:
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let lowest = i
for (let j = i + 1; j < arr.length; j++) {
if (arr[lowest] > arr[j]) {
lowest = j
}
}
if (i !== lowest) {
let temp = arr[i]
arr[i] = arr[lowest]
arr[lowest] = temp
}
}
return arr
}
console.log(selectionSort([1, -2, 33, 11, 5]))
😊😊😊😊😊😊😊😊
Insertion Sort:
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
for (let j = i; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
let temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
} else {
break
}
}
}
return arr
}
console.log(insertionSort([2, 9, -1, 22, -11, 29])) //-11, -1, 2, 9, 22, 29
Top comments (0)