[DA] Binary Search

Binary Search(์ด์ง„ ํƒ์ƒ‰)

  1. ์ •๋ ฌ ๋˜์–ด์žˆ๋Š” ์š”์†Œ๋“ค์„ ๋ฐ˜์”ฉ ์ œ์™ธํ•˜๋ฉฐ ์ฐพ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
  2. ๋ฐ˜๋“œ์‹œ ์ •๋ ฌ์ด ๋˜์–ด์žˆ์–ด์•ผ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
  3. Array, Binary Tree ๋กœ ๊ตฌํ˜„ ๊ฐ€๋Šฅ

Array ๊ตฌํ˜„

const array = [1, 1, 5, 124, 400, 599, 1004, 2876, 8712];

function binarySearch(array, findValue) {
  let left = 0;
  let right = array.length - 1;
  let mid = Math.floor((left + right) / 2);

  while (left < right) {
    if (array[mid] === findValue) {
      return mid;
    }

    if (array[mid] < findValue) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }

    mid = Math.floor((left + right) / 2);
  }

  return -1;
}

Binary Tree ๊ตฌํ˜„

์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋Š” ๋ฃจํŠธ๋ณด๋‹ค ์ž‘์€ ๊ฐ’, ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋Š” ๋ฃจํŠธ๋ณด๋‹ค ํฐ ๊ฐ’

class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor() {
    this.root = null;
  }

  insert(value) {
    const newNode = new Node(value);
    if (this.root === null) {
      this.root = newNode;
      return;
    }

    let currentNode = this.root;
    while (currentNode !== null) {
      if (currentNode.value < value) {
        if (currentNode.right == null) {
          currentNode.right = newNode;
          break;
        }
        currentNode = currentNode.right;
      } else {
        if (currentNode.left === null) {
          currentNode.left = newNode;
          break;
        }
        currentNode = currentNode.left;
      }
    }
  }

  has(value) {
    let currentNode = this.root;
    while (currentNode !== null) {
      if (currentNode.value === value) {
        return true;
      }

      if (currentNode.value < value) {
        currentNode = currentNode.right;
      } else {
        currentNode = currentNode.left;
      }
    }

    return false;
  }
}

Categories:

Updated:

Leave a comment