6. 查找(2题)
<h1>顺序查找,请实现顺序查找函数int seqSearch(int* R, int n, int k)</h1>
<pre><code class="language-c">int seqSearch(int* R, int n, int k){
int i;
for(i=0; i&lt;n; i++){
if(R[i]==k){
return i;
}
}
return -1;
}</code></pre>
<pre><code class="language-python"># 从R中查找k第几个
def seqSearch(R, k):
# 补全代码
n = len(R)
for i in range(n):
if R[i] == k:
return i
return -1</code></pre>
<h1>二分查找,请实现顺序查找函数int bSearch(int* R, int n, int k)</h1>
<pre><code class="language-c">int bSearch(int* R, int n, int k){
int low, high, mid;
low = 0;
high = n-1;
while(low&lt;=high){
mid = (low+high)/2;
if(R[mid]==k){
return mid;
}
if(R[mid]&gt;k){
high = mid-1;
}else{
low = mid+1;
}
}
return -1;
}</code></pre>
<pre><code class="language-python">def bSearch(R, k):
# 补全代码
n = len(R)
m1 = 0
m2 = n-1
while m1&lt;=m2:
mid = (m1+m2)//2
if R[mid]==k:
return mid
if R[mid]&gt;k:
m2=mid-1
else:
m1=mid+1
return -1</code></pre>