# Linear Search

### Basic Linear Search&#x20;

In linear search, each element of the array is scanned through a for loop and is checked if it same as the element that is to be found i.e key. If found, the index at which the element was found is returned or else, -1 is returned.

**Time Complexity : O(n)**

```c
int linearSearch(struct Array arr, int key) {
    
    for (int i = 0; i < arr.length; i++) {
        if (arr.A[i] == key) {
            return i;
        }
    }
    return -1;
    
}
```

### Improving Linear Search

Linear search can be improved by two techniques :&#x20;

* Transposition method
* Move to head

### Transposition Method

This method works on the concept that if an element is searched for in an array, chances are that it may be searched for again. Therefore, before returning the index of found element, we swap the element with (i-1)th element and return i-1 instead of i.

```c
int linearSearch(struct Array *arr, int key) {

    for (int i = 0; i < arr -> length; i++) {
        if (arr -> A[i] == key) {
            swap(&arr -> A[i], &arr -> A[i-1]);
            return i-1;
        }
    }
    return -1;    

}

void swap(int *x, int *y) {
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
```

### Move to Head

This method is similar to transposition method except that the found element is swapped with first element i.e 0th index element instead of (i-1)th element. This reduces the time complexity on searching the same element to O(1).

```c
int linearSearch(struct Array *arr, int key) {

    for (int i = 0; i < arr -> length; i++) {
        if (arr -> A[i] == key) {
            swap(&arr -> A[i], &arr -> A[0]);
            return 0;
        }
    }
    return -1;    

}

void swap(int *x, int *y) {
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
```

Contributed by Nitin Ranganath


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nitinranganath.gitbook.io/data-structures/arrays/linear-search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
