SimuVedaAlgorithms Lab Open in the lab

Searching / Beginner

Linear Search Visualizer

Check every value from left to right until you find the target or run out of values.

Start the Linear Search simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.

Time and space complexity

Best timeO(1)
Average timeO(n)
Worst timeO(n)
Extra spaceO(1)

Worked example, step by step

The same steps the simulator shows, on a small input.

  1. Look for 63 by checking each value from the left. [3, 8, 15, 23, 42, 51, 63, 77, 90]
  2. Is a[0] = 3 equal to 63? No.
  3. Is a[1] = 8 equal to 63? No.
  4. Is a[2] = 15 equal to 63? No.
  5. Is a[3] = 23 equal to 63? No.
  6. Is a[4] = 42 equal to 63? No.
  7. Is a[5] = 51 equal to 63? No.
  8. a[6] is 63. Found it after 7 checks. Return 6.

Try it with your own input →

Linear search in Java, Python, C++, C and JavaScript

int linearSearch(int[] a, int target) {
  for (int i = 0; i < a.length; i++) {
    if (a[i] == target) return i;
  }
  return -1;
}
def linear_search(a, target):
    for i in range(len(a)):
        if a[i] == target:
            return i
    return -1
int linearSearch(const vector<int>& a, int target) {
  for (int i = 0; i < (int)a.size(); i++) {
    if (a[i] == target) return i;
  }
  return -1;
}
int linearSearch(int a[], int n, int target) {
  for (int i = 0; i < n; i++) {
    if (a[i] == target) return i;
  }
  return -1;
}
function linearSearch(a, target) {
  for (let i = 0; i < a.length; i++) {
    if (a[i] === target) return i;
  }
  return -1;
}

In an interview

It works on any array, sorted or not. If the array is sorted, binary search is the better answer.

More searching