如果需要知道陣列當中,是否存在某個特定的值,則可使用搜尋。 最簡單的搜尋方法,是線性搜尋(一個一個找):

#include <stdio.h>

#define SIZE 100

int linearSearch(int a[], int size, int key){
	int i;

	for(i=0;i<size;i++){
		if(a[i]==key){
			return i;
		}
	}
	return -1;
}

int main()
{
	int i, position, key = 37;
	int a[SIZE] = {0};

	/* 產生數字 */
	for(i=0;i<SIZE;i++){
		a[ i ] = i * 2;
	}

	position = linearSearch(a, SIZE, key);

	if(position>=0){
		printf("Found %d in a[%d]\n", key, position);
	}
	else {
		printf("Not found\n");
	}

	return 0;
}

如果陣列已經被排序過,則可使用二元搜尋法:

#include <stdio.h>

#define SIZE 100

int binarySearch(int a[], int size, int key){
	int low = 0, center, high = size - 1;

	while(low<=high){
		center = (low+high)/2;
		if(a[center]==key){
			return center;
		}
		else if(key<a[center]){
			high = center - 1;
		}
		else {
			low = center + 1;
		}
	}
	return -1;
}

int main()
{
	int i, position, key = 37;
	int a[SIZE] = {0};

	/* 產生數字 */
	for(i=0;i<SIZE;i++){
		a[ i ] = i * 2;
	}

	position = binarySearch(a, SIZE, key);

	if(position>=0){
		printf("Found %d in a[%d]\n", key, position);
	}
	else {
		printf("Not found\n");
	}

	return 0;
}