JSFiddle - React, Tailwind, and code Playground
JavaScript
//copié collé https://www.geeksforgeeks.org/bubble-sort/
function bubbleSort(arr) {
const n = arr.length
for (let i = 0; i < n - 1; ++i) {
for (let j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
const t = arr[j]
arr[j] = arr[j+1]
arr[j+1] = t
}
}
}
}
//copié collé aussi! https://en.wikipedia.org/wiki/Binary_search_algorithm (function binary_search(A, n, T):)
function dichot (A, T) {
let L = 0
let R = A.length - 1
while (L <= R) {
const m = Math.floor((L + R) / 2)
if (A[m] < T) {
L = m + 1
} else if (A[m] > T) {
R = m - 1
} else {
return m
}
}
return -1
}
//pas faire attention à console, juste pour affichage
console = {
log(...args){
document.querySelector('div').innerHTML += '<p>'+args.join(' ')+'</p>'
}
}
//on teste quelques cas
var arr = [1,2,3,5,6,1,4]
bubbleSort(arr)
console.log('arr: ', arr.join(' '))
console.log('7? doit retourner -1 -> ', dichot(arr, 7))
// on retourne bien l'index de la valeur
var arr = [1,2,5,6,1,4]
bubbleSort(arr)
console.log('arr: ', arr.join(' '))
console.log('5? doit retourner 4 -> ', dichot(arr, 5))
// on trouve en cas de début de tableau
var arr = [1,2,3,5,6,1,4]
bubbleSort(arr)
console.log('arr: ', arr.join(' '))
console.log('1? doit retourner 0 ou 1 -> ', dichot(arr, 1))
// on trouve en cas de fin de tableau
var arr = [1,2,3,5,7,1,4]
bubbleSort(arr)
console.log('arr: ', arr.join(' '))
console.log('7? doit retourner 6 -> ', dichot(arr, 7))