Linear search

Algorithms / Search

//Time Complexity O(n)
//the plain scan: compare element after element
int search(const int arr[], size_t count, int x) {
    size_t i = 0;
    while (i < count) {
        if (arr[i] == x) {
            return (int)i;
        }
        i++;
    }
    return -1;
}

int items[] = {2, 3, 5, 7, 11, 13, 17};
size_t count = sizeof items / sizeof items[0];

int index1 = search(items, count, 1);
//index1 is -1
int index7 = search(items, count, 7);
//index7 is 3
int index19 = search(items, count, 19);
//index19 is -1

printf("index1 is %d\n", index1);
printf("index7 is %d\n", index7);
printf("index19 is %d\n", index19);