Home
37 二分查找法
Learning Processing
37 二分查找法
姜睿
姜睿
September 21, 2022
1 min

Table Of Contents

01
顺序查找法
02
代码实现
03
缺点

顺序查找法

1
2int[] array = {0, 1, 2, 3, 4, 5};
3
4void setup() {
5// 5
6println(ordersearch(array, 5));
7}
8
9int ordersearch(int[] arr, int des) {
10for (int i = 0; i < arr.length; i++) {
11if (des == arr[i])
12return i;
13}
14return -1;
15}
16

代码实现

  • 防止溢出1
1
2int[] array = {0, 2, 4, 7, 9, 10, 14};
3// int[] _i = {0, 1, 2, 3, 4, 5 , 6};
4
5void setup() {
6// output: -1
7println(BinarySearch(array, 5));
8// output: 2
9println(BinarySearch(array, 4));
10// output: 3
11println(BinarySearch(array, 7));
12// output: 5
13println(BinarySearch(array, 10));
14}
15
16int BinarySearch(int[] arr, int start, int end, int _key) {
17// cannot find
18if (start > end)
19return -1;
20// cal mid index
21int mid = start + (end - start) / 2;
22if (arr[mid] > _key)
23return BinarySearch(arr, start, mid - 1, _key);
24if (arr[mid] < _key)
25return BinarySearch(arr, mid + 1, end, _key);
26return mid;
27}
28
29int BinarySearch(int[] arr, int _key) {
30return BinarySearch(arr, 0, arr.length, _key);
31}
32

缺点

  • 待查表为有序表。

  1. Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken

Tags

#game develop
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

42 快速排序
42 快速排序
October 01, 2022
1 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use