顺序查找:线性查找,从前往后依次查找,直到找到匹配的值,返回键值或其下标;若无匹配值返回 -1。代码如下:
<pre name="code" class="java"><span style="font-family:Arial;font-size:18px;">public class LinearSearch{
<span style="white-space: pre;"> </span>public static int linearSearch(int[] list, int key){</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>for(int i=0;i<list.length;i++){</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>if(key==list[i]) return i;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>}</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>return -1;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space: pre;"> </span>}
}</span>
<span style="font-family:Arial;font-size:18px;">
</span>
<span style="font-family:Arial;font-size:18px;">二分查找:适合有序数组。键值和数组中间元素比较,若小于中间元素,查找前半部分的中间元素与之比较,反之查找后半部分;依次类推,直到找到为止。</span>
<span style="font-family:Arial;font-size:18px;">public class BinarySearch{</span>
<span style="white-space:pre"> </span><span style="font-family:Arial;font-size:18px;">public static int binarySearch(int[] list, int key){</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span> <span style="white-space:pre"> </span>int low=0;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>int high=list.length-1;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>while(high>=low){</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>int mid=(low+high)/2;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>if(key<list[mid])</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>high=mid-1;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>else if(key==list[mid])</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>return mid;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>else</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>low=mid+1;</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>}</span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>return -low-1;<span style="white-space:pre"> </span></span>
<span style="font-family:Arial;font-size:18px;"><span style="white-space:pre"> </span>}</span>
</pre><pre name="code" class="java">
<span style="font-family:Arial;font-size:18px;">}</span>