对于数据的排序要根据数据的特征来选择算法,对于已排序好的数据,一般使用二分查找是效率高的一种选择。
#include <stdio.h>
int main() {
int num[] = {2, 3, 4, 5, 6, 7, 8, 10, 12, 18, 20}, len = 11;
int f = find(num, len, 12);
printf("%d", f);
}
int find(int num[], int len, int find) {
if (NULL == num || len == 0)
return;
int start = 0;
int end = len - 1;
while (start <= end) {
int middle = start + ((end - start) >> 1);
if (find == num[middle])
return middle;
else if (find > num[middle])
start = middle + 1;
else
end = middle - 1;
}
return -1;
}