Binary Serach_์ด๋ถ๊ฒ์
๐ต ThingsILearned
โ๏ธ ์ด๋ถ๊ฒ์
์ด๋ถ๊ฒ์: ๊ฒ์ํ ๋ฒ์๋ฅผ ๋ฐ์ผ๋ก ์ค์ฌ๊ฐ๋ฉฐ ์ฐพ๋ ๊ฒ์ โญ๏ธโญ๏ธโญ๏ธ ์ด๋ถ๊ฒ์์ ์ ๋ ฌ์ด ๋ ์ํ์์ ์์ํ๋ค. ์ด๋ถ๊ฒ์์ ์๊ฐ๋ณต์ก๋๋ O(log n)
์ด๋ถ๊ฒ์์ ํ ๋๋
์ฐพ๋ ๊ฐ, ์์ ์์น, ์ข
๋ฃ ์์น๋ฅผ ์ํ์ผ ํ๋ค.
์ค๊ฐ ์์น๋ฅผ ์ฐพ์ ๋๋ (์์ ์์น + ์ข
๋ฃ ์์น) /2
์ด ์ค๊ฐ ์์น
๊ฐ ์ฐพ๋ ๊ฐ๊ณผ ๊ฐ๋ค๋ฉด ๊ฒ์ ์ข
๋ฃ,
์ฐพ๋ ๊ฐ๋ณด๋ค ์๋ค๋ฉด ๋ฐฐ์ด์ ์ค๋ฅธ์ชฝ(๋ ํฐ ์ชฝ) ๊ฒ์
์ฐพ๋ ๊ฐ๋ณด๋ค ํฌ๋ค๋ฉด ๋ฐฐ์ด์ ์ผ์ชฝ(๋ ์์ ์ชฝ) ๊ฒ์
โ n๊ฐ์ ์๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ ๋ค์ m์ด ์ด๋์๋์ง ์ด๋ถ๊ฒ์์ผ๋ก ๊ตฌํ์ธ์.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.ct_inflean_2024.String;
import java.util.*;
class Main {
public int solution(int n, int m, int[] input){
int answer=0;
Arrays.sort(input); //์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
int start=0;
int end= n-1;
while(start<=end){
int middle= (start+end)/2;
if(m == input[middle]){
answer= middle+1;
break;
}
if(m < input[middle]){
end= middle-1;
}else{
start=middle+1;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int m= sc.nextInt();
int[] input= new int[n];
for(int i=0; i<n; i++){
input[i]= sc.nextInt();
}
System.out.println(T.solution(n, m, input));
}
}
//โญ๏ธinput:
8 32
23 87 65 12 57 32 99 81
//โญ๏ธoutput:
3
๐ข
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Main {
public int solution(int n, int m, int[] input){
int answer=0;
Arrays.sort(input); //์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
int start=0;
int end= n-1;
int middle= (int) (start+end)/2;
while(m != input[middle]){
if(m < input[middle]){
end= middle-1;
middle= (int) (start+end)/2;
}else{
start=middle+1;
middle= end;
}
}
answer= middle+1;
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int m= sc.nextInt();
int[] input= new int[n];
for(int i=0; i<n; i++){
input[i]= sc.nextInt();
}
System.out.println(T.solution(n, m, input));
}
}
This post is licensed under CC BY 4.0 by the author.