Binary Search

Problem

Any N numbers are given as input. Write a program that sorts N numbers in ascending order and, given M, which is one of the N numbers, uses binary search to find the number of M in the sorted state. However, there are no duplicate values.

input

  • The first line gives the natural numbers N (3<=N<=1,000,000) and M per line
  • In the second line, N numbers are given with a space between them
8 32

23 87 65 12 57 32 99 81

output

Prints the position number of the value of M after sorting on the first line.

3

Solution

function solution(target, arr) {
	let answer,
		lt = 0,
		rt = arr.length - 1;

	arr.sort((a, b) => a - b);

	while (lt <= rt) {
		let mid = parseInt((lt + rt) / 2);
		if (arr[mid] === target) {
			answer = mid + 1;
			break;
		} else if (arr[mid] > target) rt = mid - 1;
		else lt = mid + 1;
	}

	return answer;
}