1.问题
在一个排好顺序的数组中查找x,如果x在该数组中,则输出其下标,否则输出0。使用顺序查找的二分查找来分别完成
2.解析
顺序查找是对每一个数进行比较,直到找到该数,或者遍历以后未找到则输出0.
二分查找是在数组有序的前提下,通过查找中间数,并与待查数比较以减小区间的方式,来找到该数。
3.设计
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
#define number 10000
int comp(const void* p, const void* q) {
return (*reinterpret_cast<const int*>(p) - *reinterpret_cast<const int*>(q));
}
int main() {
int a[number], i, j, k, n;
srand(time(NULL));
for (i = 0; i < number; i++) {
a[i] = rand();
}
n = rand();
qsort(a, number, sizeof(int), comp);
//顺序查找
for (i = 0; i < number; i++) {
if (a[i] == n) {
break;
}
}
if (i == number) {
cout << 0 << endl;
}
else {
cout << i + 1 << endl;
}
//二分查找
i = 0;
j = number-1;
while (i <= j) {
k = (i + j) / 2;
if (n == a[k]) {
break;
}
else if (n < a[k]) {
j = k - 1;
}
else {
i = k + 1;
}
}
if (i > j) {
cout << 0 << endl;
}
else {
cout << k + 1 << endl;
}
}
4.分析
顺序查找复杂度:O(n) 二分查找复杂度:O(logn)