2分検索ファンクションのVBAソースコードを紹介します。配列の最初から順番に目的の要素を探す場合は、最大でN回の比較検索が必要です。しかしこの2分検索アルゴリズムは最大でlog*N回の比較検索で探します。何度も言いますがソートなどの並び替えと同じく、アルゴリズムを構築する場合はとても長い配列を想定しなければいけません。
アルゴリズムとシステムについて:少し内容が逸れます。 アルゴリズムは「システム」とは違い失敗や漏れがあってはアルゴリズムとして成り立ちません。そういった理に適っている洗練されたアルゴリズムは人類のとても貴重な財産です。宝石やお金などの光り物は常に価値が変動したり時に失ったりすることがありますが、理となって顕現しているものは決して動いたり失うことがありません。不動の理(支点)がないと何も動かすことが出来ません。一方、ビジネスのツールや社会のルールとなるシステムは時間の経過と共にに想定外の事態が起こった場合、切捨てなければならない部分が生じます。株価の例を挙げると、上げ下げの材料は時間にほぼ比例するように増えていきます。
もしすべての条件を最初から想定できる社会システムを創ることが出来れば、公共の福祉(弱者救済)のための司法機関は必要なくなるでしょう。残念ながらシステムである以上それはありえません。通常、システムは常に多数を選択します。それでコツコツと(多数と少数の)鞘の部分に貯まりだす利益を生み出します。
話が逸れましたが、アルゴリズムはとても価値あるもので人生というジグソーパズルの中の定まった貴重なパーツにもなりうるということを理解してください。
The VBA source code of "Binary search" function is shown below.To find for the target element in an order from the beginning of array, N comparison search is required at the maximum. However, this "Binary search" algorithm will find target element at log*N time at the maximum. Although repeatedly said, when building an algorithm, you have to assume very long array.
About an algorithm and a system: The contents swerve for a while. Algorithm is different from "System", and bugs never occur in the algorithm. Such refined rational algorithms are human beings' very precious property. Although value jewelry or money may always fluctuate,and also may sometimes be lost, algorithm is truth and it will never change, or is not lost. Anything can be moved if there is no immovable truth (fulcrum). On the other hand, when the situation besides assumption happens to progress of time, the portion which must be cut off when produces the system used as the tool of business, or a social rule. If the example of a stock price is given, the material of taking up and down will increase mostly proportional to time.
The machinery of law for public welfare will become unnecessary if the social system which can assume all the conditions from the beginning can be predicted. Though regrettable, a system cannot be created perfectly like algorithm. Usually, a system always chooses a large number. After then, the profits (a large number and small number) which begin to accumulate in the portion of a difference are produced.
What I meant was, I want you to understand that an algorithm is very valuable and it can also become the fixed precious part of a jigsaw puzzle in your life.
ソースコードを紹介します。ヒープソートなどと比べるととても簡単なものです。
この2分検索ファンクション(Binary_Search)は、配列の中の真ん中の位置を指定しながらKey(配列の中から検索する要素)を探します。最初に指定する位置は、(0+12)/2=6 なので7番目の位置にある要素「6」になります。(0は配列の頭、12は配列の最後)
下の例は、配列の中の3を2分検索しています。
This example show how binary search find the key from array.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|
真ん中の6以上の可能性がなくなりましたので、次に(0+5)/2=2 とKeyを比較します。
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
次に、3以下の位置である可能性がなくなりましたので、(3+5)/2=4 とKeyを比較します。
| 3 | 4 | 5 |
|---|
次に、4以上の位置である可能性がなくなりましたので、(3+3)/2=3 とKeyを比較します。そこで見つけることが出来ました。このとき最後まで残ったので、比較したのlog*N 回です。もし配列の最初から見つけた場合は最大でN回の比較検索が必要です。
| 3 |
Search