﻿ 有效搜索元素的方法 - 代码日志

#### 有效搜索元素的方法

Assume there is an array of (positive) integers, of which each element is either `+1` or `-1` compared to its adjacent elements.

Example:

06000

Now search for `7` and return its position.

Store the values in a temporary array, sort them, and then apply binary search.

If the element is found, return its position in the temporary array.
(If the number is occurring twice then return its first occurrence)

``````#include <stdio.h>
#include <stdlib.h>

int first_occurence(int k, int array[], int n);

int main(void){
int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8};
printf("7 first occurs at index %d\n",first_occurence(7,a,15));
printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15));
return 0;
}

int first_occurence(int k, int array[], int n){
int i = 0;
while(i < n){
if(array[i] == k) return i;
i += abs(k-array[i]);
}
return -1;
}
``````

``````7 first occurs at index 11
but 9 first "occurs" at index -1
``````
http://stackoverflow.com/questions/34481582/efficient-way-to-search-an-element