SlideShare a Scribd company logo
Algorithm
Binary Search
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Linear Search
•Binary Search
•Concept
•Features
•Implementation
•References
Linear Search
Linear Search는 가장 단순한 방식의 탐색 방법입니다.
배열의 요소를 처음부터 끝까지 순차적으로 순회하며 원하는 요소
를 찾는 방식입니다.
최악의 경우는 모든 배열을 순회하고 나서야 값을 찾거나 찾지 못
할 수 있습니다.
따라서 시간복잡도가 0(n)이 될 수 있는 알고리즘입니다.
Binary Search
Binary Search이란 이진 탐색으로서 단순한 선형 탐색(Linear
Search)와 달리 절반씩 배열을 줄여나가면서 찾는 탐색 알고리즘
입니다.
단 이진 탐색 알고리즘을 실행하기 위해서는 배열의 요소가 정렬이
되어있어야 하는 단점이 있습니다.
Concept
이진 탐색의 과정을 보면 아래와 같은 방식으로 탐색을 합니다.
1. 배열의 중앙 값(middle
index)을 찾습니다.
2. 찾고자하는 값과 중앙값
을 비교하여 작으면 왼쪽,
크면 오른쪽의 요소들의 배
열의 중앙값을 다시 찾습
니다.
3. 현재 중앙값의 요소와 찾
고자하는 값을 계속 비교
하며 찾을때까지 2번의 과
정을 반복합니다.
Features
이진 탐색은 아래와 같은 특징을 가진 알고리즘입니다.
1. 기본적으로 배열을 절반으로 나누면서 탐색을 하는 방식
2. 탐색 전에 배열이 정렬이 되어 있어야 함
3. 시간복잡도는 O(logn)의 속도를 가짐
4. 알고리즘의 복잡도가 높지 않으며 효율이 선형 탐색보다 좋음
Implementation
Swift를 활용하여 이진 탐색 알고리즘을 살펴보겠습니다.
아래는 기본적으로 오른차순으로 정렬된 배열을 기준으로하여 탐색
하는 알고리즘이니다.
func binarySearch<T: Comparable>(array: [T], item: T) -> Int {
var low = 0
var high = array.count - 1
while low <= high {
let mid = (low + high) / 2
let guess = array[mid]
if guess == item {
return mid
} else if guess > item {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
Implementation
아래와 같이 재귀 호출 방식으로도 이진 탐색 알고리즘을 구현할
수 있습니다.
func binarySearch(first: Int, last: Int, target: Int, array: [Int]) -> Int {
if first > last {
return -1
}
let middle = (first + last) / 2
if target == array[middle] {
return middle
} else {
if target < array[middle] {
return binarySearch(first: first, last: middle-1, target: target,
array: array)
} else {
return binarySearch(first: middle+1, last: last, target: target,
array: array)
}
}
}
Implementation
let numbers = [-1, 0, 1, 2, 5, 13, 15, 20, 45, 51, 59, 68, 77]
print("Index : (binarySearch(array: numbers, item: 1))") // Index : 2
print("Index : (binarySearch(array: numbers, item: 68))") // Index : 11
print("Index : (binarySearch(array: numbers, item: 99))") // Index : -1
print("Index : (binarySearch(first: 0, last: numbers.count, target: 1, array:
numbers))") // Index : 2
References
[1] [Swift] Swift로 Binary Search( 이진 탐색 알고리즘 )를 구
현해보자 : https://eunjin3786.tistory.com/32
[2] Play With Code: Binary Search In Swift : https://
learnappmaking.com/binary-search-swift-how-to/
[3] Swift, Algorithm, linear Search & Binary Search :
https://devmjun.github.io/archive/BinarySearch
[4] How to implement Binary Search in Swift? : https://
medium.com/@notestomyself/how-to-implement-binary-
search-in-swift-6867840302ed
[5] Divide and Conquer with Binary Search in Swift :
https://mikebuss.com/2016/04/21/binary-search/
References
[6] Binary Search Array Extension in Swift : https://
agostini.tech/2017/01/30/binary-search-array-
extension-in-swift/
[7] Swift Algorithms – Binary Search : https://
www.seemuapps.com/swift-algorithms-binary-search
[8] 이진 검색(Binary Search) : https://kka7.tistory.com/77
[9] Algorithm) 이진 탐색(Binary Search) in Swift : https://
atelier-chez-moi.tistory.com/88
[10] [스위프트:알고리즘] 이진 탐색[1 / 3]: Binary Search: 이진
탐색이 뭐야? : https://the-brain-of-sic2.tistory.com/42
References
[11] Swift로 자료구조, 알고리즘 공부하기 (1) - Binary
Search : https://kor45cw.tistory.com/1
Thank you!

More Related Content

What's hot (19)

파이썬 자료형 발표
파이썬 자료형 발표
joonjhokil
 
110120 binary search
110120 binary search
Yeayoung Ha
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort
Bill Kim
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
Bill Kim
 
R과 기초통계 : 01.자료다루기
R과 기초통계 : 01.자료다루기
Yoonwhan Lee
 
R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기
Yoonwhan Lee
 
R 기초 : R Basics
R 기초 : R Basics
Yoonwhan Lee
 
Python 스터디
Python 스터디
sanghyuck Na
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
Bill Kim
 
통계자료 분석을 위한 R
통계자료 분석을 위한 R
Yoonwhan Lee
 
Start IoT with JavaScript - 4.객체1
Start IoT with JavaScript - 4.객체1
Park Jonggun
 
제4장 sql 함수를 사용해보기
제4장 sql 함수를 사용해보기
sang doc Lee
 
Haskell study 4
Haskell study 4
Nam Hyeonuk
 
Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자
Park Jonggun
 
R 기초 II
R 기초 II
Yoonwhan Lee
 
Scala스터디 - 배열사용하기
Scala스터디 - 배열사용하기
창규 김
 
알고리즘 스터디(정렬) Seungdols
알고리즘 스터디(정렬) Seungdols
seungdols
 
파이썬 자료형 발표
파이썬 자료형 발표
joonjhokil
 
110120 binary search
110120 binary search
Yeayoung Ha
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort
Bill Kim
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
Bill Kim
 
R과 기초통계 : 01.자료다루기
R과 기초통계 : 01.자료다루기
Yoonwhan Lee
 
R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기
Yoonwhan Lee
 
R 기초 : R Basics
R 기초 : R Basics
Yoonwhan Lee
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
Bill Kim
 
통계자료 분석을 위한 R
통계자료 분석을 위한 R
Yoonwhan Lee
 
Start IoT with JavaScript - 4.객체1
Start IoT with JavaScript - 4.객체1
Park Jonggun
 
제4장 sql 함수를 사용해보기
제4장 sql 함수를 사용해보기
sang doc Lee
 
Start IoT with JavaScript - 2.연산자
Start IoT with JavaScript - 2.연산자
Park Jonggun
 
Scala스터디 - 배열사용하기
Scala스터디 - 배열사용하기
창규 김
 
알고리즘 스터디(정렬) Seungdols
알고리즘 스터디(정렬) Seungdols
seungdols
 

Similar to [Algorithm] Binary Search (20)

04. binary search
04. binary search
승혁 조
 
Binary search
Binary search
Minsuk Lee
 
Binary Search
Binary Search
skku_npc
 
[데브루키]노대영_알고리즘 스터디
[데브루키]노대영_알고리즘 스터디
대영 노
 
알고리즘
알고리즘
승우 백
 
Data Structure - 1st Study
Data Structure - 1st Study
Chris Ohk
 
Algorithms summary korean
Algorithms summary korean
Young-Min kang
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
Bill Kim
 
Equation Solving
Equation Solving
Jeong-Hoon Mo
 
Line sweep algorithms
Line sweep algorithms
skku_npc
 
Shell, merge, heap sort
Shell, merge, heap sort
Hyun Jin Moon
 
[0521 석재호]백트래킹알고리즘
[0521 석재호]백트래킹알고리즘
Jaeho Seok
 
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
Isaac Jeon
 
세미나
세미나
Dongyi Kim
 
1.3장 차수 높은 프로시저(higher order procedure)로 요약하는 방법
1.3장 차수 높은 프로시저(higher order procedure)로 요약하는 방법
홍준 김
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)
fmbvbfhs
 
[SOPT] 데이터 구조 및 알고리즘 스터디 - #01 : 개요, 점근적 복잡도, 배열, 연결리스트
[SOPT] 데이터 구조 및 알고리즘 스터디 - #01 : 개요, 점근적 복잡도, 배열, 연결리스트
S.O.P.T - Shout Our Passion Together
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
Yong Joon Moon
 
[D2CAMPUS] Algorithm tips - ALGOS
[D2CAMPUS] Algorithm tips - ALGOS
NAVER D2
 
양성봉 - 알기쉬운 알고리즘 - 1장알고리즘의첫걸음
양성봉 - 알기쉬운 알고리즘 - 1장알고리즘의첫걸음
Dongseo University
 
04. binary search
04. binary search
승혁 조
 
Binary Search
Binary Search
skku_npc
 
[데브루키]노대영_알고리즘 스터디
[데브루키]노대영_알고리즘 스터디
대영 노
 
Data Structure - 1st Study
Data Structure - 1st Study
Chris Ohk
 
Algorithms summary korean
Algorithms summary korean
Young-Min kang
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
Bill Kim
 
Line sweep algorithms
Line sweep algorithms
skku_npc
 
Shell, merge, heap sort
Shell, merge, heap sort
Hyun Jin Moon
 
[0521 석재호]백트래킹알고리즘
[0521 석재호]백트래킹알고리즘
Jaeho Seok
 
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
NDC 2018 억! 소리나는 게임 서비스 플랫폼을 지탱하는 알고리즘 - 해시, 불변데이터, 확률적 자료구조
Isaac Jeon
 
세미나
세미나
Dongyi Kim
 
1.3장 차수 높은 프로시저(higher order procedure)로 요약하는 방법
1.3장 차수 높은 프로시저(higher order procedure)로 요약하는 방법
홍준 김
 
1.자료구조와 알고리즘(강의자료)
1.자료구조와 알고리즘(강의자료)
fmbvbfhs
 
[SOPT] 데이터 구조 및 알고리즘 스터디 - #01 : 개요, 점근적 복잡도, 배열, 연결리스트
[SOPT] 데이터 구조 및 알고리즘 스터디 - #01 : 개요, 점근적 복잡도, 배열, 연결리스트
S.O.P.T - Shout Our Passion Together
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
Yong Joon Moon
 
[D2CAMPUS] Algorithm tips - ALGOS
[D2CAMPUS] Algorithm tips - ALGOS
NAVER D2
 
양성봉 - 알기쉬운 알고리즘 - 1장알고리즘의첫걸음
양성봉 - 알기쉬운 알고리즘 - 1장알고리즘의첫걸음
Dongseo University
 
Ad

More from Bill Kim (20)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
Bill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation
Bill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort
Bill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort
Bill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort
Bill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort
Bill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
Bill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
Bill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
Bill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
Bill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
Bill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
Bill Kim
 
[Swift] Data Structure - Dequeue
[Swift] Data Structure - Dequeue
Bill Kim
 
[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
Bill Kim
 
[Swift] Data Structure - Queue
[Swift] Data Structure - Queue
Bill Kim
 
[Swift] Data Structure - Linked List
[Swift] Data Structure - Linked List
Bill Kim
 
[Swift] Data Structure Introduction
[Swift] Data Structure Introduction
Bill Kim
 
Design Pattern Introduction
Design Pattern Introduction
Bill Kim
 
[Swift] Visitor
[Swift] Visitor
Bill Kim
 
[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
Bill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation
Bill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort
Bill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort
Bill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort
Bill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort
Bill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
Bill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
Bill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
Bill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
Bill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
Bill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
Bill Kim
 
[Swift] Data Structure - Dequeue
[Swift] Data Structure - Dequeue
Bill Kim
 
[Swift] Data Structure - Stack
[Swift] Data Structure - Stack
Bill Kim
 
[Swift] Data Structure - Queue
[Swift] Data Structure - Queue
Bill Kim
 
[Swift] Data Structure - Linked List
[Swift] Data Structure - Linked List
Bill Kim
 
[Swift] Data Structure Introduction
[Swift] Data Structure Introduction
Bill Kim
 
Design Pattern Introduction
Design Pattern Introduction
Bill Kim
 
[Swift] Visitor
[Swift] Visitor
Bill Kim
 
Ad

[Algorithm] Binary Search

  • 3. Linear Search Linear Search는 가장 단순한 방식의 탐색 방법입니다. 배열의 요소를 처음부터 끝까지 순차적으로 순회하며 원하는 요소 를 찾는 방식입니다. 최악의 경우는 모든 배열을 순회하고 나서야 값을 찾거나 찾지 못 할 수 있습니다. 따라서 시간복잡도가 0(n)이 될 수 있는 알고리즘입니다.
  • 4. Binary Search Binary Search이란 이진 탐색으로서 단순한 선형 탐색(Linear Search)와 달리 절반씩 배열을 줄여나가면서 찾는 탐색 알고리즘 입니다. 단 이진 탐색 알고리즘을 실행하기 위해서는 배열의 요소가 정렬이 되어있어야 하는 단점이 있습니다.
  • 5. Concept 이진 탐색의 과정을 보면 아래와 같은 방식으로 탐색을 합니다. 1. 배열의 중앙 값(middle index)을 찾습니다. 2. 찾고자하는 값과 중앙값 을 비교하여 작으면 왼쪽, 크면 오른쪽의 요소들의 배 열의 중앙값을 다시 찾습 니다. 3. 현재 중앙값의 요소와 찾 고자하는 값을 계속 비교 하며 찾을때까지 2번의 과 정을 반복합니다.
  • 6. Features 이진 탐색은 아래와 같은 특징을 가진 알고리즘입니다. 1. 기본적으로 배열을 절반으로 나누면서 탐색을 하는 방식 2. 탐색 전에 배열이 정렬이 되어 있어야 함 3. 시간복잡도는 O(logn)의 속도를 가짐 4. 알고리즘의 복잡도가 높지 않으며 효율이 선형 탐색보다 좋음
  • 7. Implementation Swift를 활용하여 이진 탐색 알고리즘을 살펴보겠습니다. 아래는 기본적으로 오른차순으로 정렬된 배열을 기준으로하여 탐색 하는 알고리즘이니다. func binarySearch<T: Comparable>(array: [T], item: T) -> Int { var low = 0 var high = array.count - 1 while low <= high { let mid = (low + high) / 2 let guess = array[mid] if guess == item { return mid } else if guess > item { high = mid - 1 } else { low = mid + 1 } } return -1 }
  • 8. Implementation 아래와 같이 재귀 호출 방식으로도 이진 탐색 알고리즘을 구현할 수 있습니다. func binarySearch(first: Int, last: Int, target: Int, array: [Int]) -> Int { if first > last { return -1 } let middle = (first + last) / 2 if target == array[middle] { return middle } else { if target < array[middle] { return binarySearch(first: first, last: middle-1, target: target, array: array) } else { return binarySearch(first: middle+1, last: last, target: target, array: array) } } }
  • 9. Implementation let numbers = [-1, 0, 1, 2, 5, 13, 15, 20, 45, 51, 59, 68, 77] print("Index : (binarySearch(array: numbers, item: 1))") // Index : 2 print("Index : (binarySearch(array: numbers, item: 68))") // Index : 11 print("Index : (binarySearch(array: numbers, item: 99))") // Index : -1 print("Index : (binarySearch(first: 0, last: numbers.count, target: 1, array: numbers))") // Index : 2
  • 10. References [1] [Swift] Swift로 Binary Search( 이진 탐색 알고리즘 )를 구 현해보자 : https://eunjin3786.tistory.com/32 [2] Play With Code: Binary Search In Swift : https:// learnappmaking.com/binary-search-swift-how-to/ [3] Swift, Algorithm, linear Search & Binary Search : https://devmjun.github.io/archive/BinarySearch [4] How to implement Binary Search in Swift? : https:// medium.com/@notestomyself/how-to-implement-binary- search-in-swift-6867840302ed [5] Divide and Conquer with Binary Search in Swift : https://mikebuss.com/2016/04/21/binary-search/
  • 11. References [6] Binary Search Array Extension in Swift : https:// agostini.tech/2017/01/30/binary-search-array- extension-in-swift/ [7] Swift Algorithms – Binary Search : https:// www.seemuapps.com/swift-algorithms-binary-search [8] 이진 검색(Binary Search) : https://kka7.tistory.com/77 [9] Algorithm) 이진 탐색(Binary Search) in Swift : https:// atelier-chez-moi.tistory.com/88 [10] [스위프트:알고리즘] 이진 탐색[1 / 3]: Binary Search: 이진 탐색이 뭐야? : https://the-brain-of-sic2.tistory.com/42
  • 12. References [11] Swift로 자료구조, 알고리즘 공부하기 (1) - Binary Search : https://kor45cw.tistory.com/1