无序数组怎么采用二分查找

-

let arr = [5,3,1,10,55,43,22];
  // 将方位角从小到大排序
  // 另外生成一个排序后每个元素在原数组中的索引
  function createSortAngles(angles){
    const sortAngles = angles.toSorted((a,b)=>a-b);
    const sortAnglesIndex = sortAngles.map(angle=>angles.indexOf(angle));
    return {
      sortAngles,
      sortAnglesIndex,
    }
  }
  const sortAngles = createSortAngles(arr);
  console.log('sortAngles', sortAngles, arr);
  function findNearesttargetber(arr, target) {
    let mid;
    let min = 0;
    let max = arr.length - 1;
    while (max - min > 1) {
      mid = Math.floor((min + max) / 2);
      if (target < arr[mid]) {
        max = mid;
      } else {
        min = mid;
      };
    };
    // return Math.abs(target - arr[min]) <= Math.abs(target - arr[max]) ? arr[min] : arr[max];
    return Math.abs(target - arr[min]) <= Math.abs(target - arr[max]) ? min : max;
  }

  console.log(findNearesttargetber(sortAngles.sortAngles, 100))

 

 

 

 

 

-

posted @ 2025-03-04 21:16  古墩古墩  Views(12)  Comments(0)    收藏  举报