Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Type Conversion C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Scope C Function Declaration C Functions Challenge C Math Functions C Inline Functions C Recursion C Function Pointers

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Structs Challenge C Nested Structures C Structs & Pointers C Unions C typedef C Struct Padding

C Enums

C Enums

C Memory

C Memory Management

C Errors

C Errors C Error Challenge C Debugging C NULL C Error Handling C Input Validation

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers

C DSA

C DSA Intro C Searching C Sorting C Stacks C Queues C Linked Lists C Trees C Big O

C Projects

C Projects

C Cert

C Certificate

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A

C DSA Searching

Share

Linear Search

Linear search is the simplest way to find a value. Check each item, one by one, from the start. Stop when you find the value, or when you reach the end.

It is like looking for your keys by checking every pocket, one after another.

Here is a linear search in C, where we search for the value 7:

Example

#include <stdio.h>

// Returns the index of the value, or -1 if it is not found
int linearSearch(int arr[], int length, int value) {
  for (int i = 0; i < length; i++) {
    if (arr[i] == value) {
      return i;
    }
  }
  return -1;
}

int main() {
  int numbers[] = {4, 9, 2, 7, 5, 8};
  int length = sizeof(numbers) / sizeof(numbers[0]);

  int index = linearSearch(numbers, length, 7);

  if (index != -1) {
    printf("Found 7 at index %d\n", index);
  } else {
    printf("7 was not found\n");
  }

  return 0;
}

Result:

Found 7 at index 3
Try it Yourself »

Run the simulation below to see how the code above works. Each column is one value in the array. The dashed line shows the value we search for (7): a column that reaches exactly up to the line has that value.

When you run the simulation, the yellow column is the one being checked. Grey columns did not match. If the value is found, its column turns green.

Linear search works on any array, sorted or not. But it can be slow. If the array has 1,000,000 items, you might have to check all 1,000,000 of them!


Binary Search

Binary search is much faster, but it only works on a sorted array. Here is how it works:

  1. Look at the item in the middle.
  2. If it is the value you want, you are done!
  3. If the value you want is bigger, search only the right half. If it is smaller, search only the left half.
  4. Repeat with the half that is left.

Every step throws away half of the items. Here we search for 23. The middle item is yellow, and grey items are already thrown away:

Binary search for 23 in the sorted array 2, 5, 8, 12, 16, 23, 38, 56, 72, 91. Step 1 checks the middle, 16 at index 4. 23 is bigger, so the left half is thrown away. Step 2 checks 56 at index 7. 23 is smaller, so the right part is thrown away. Step 3 checks index 5 and finds 23. Step 1 Step 2 Step 3 0 1 2 3 4 5 6 7 8 9 2 5 8 12 16 23 38 56 72 91 2 5 8 12 16 23 38 56 72 91 2 5 8 12 16 23 38 56 72 91

Three steps, and we found it!

Run the simulation below. It uses the same sorted array as the picture, and searches for 23 again. The value axis lists the values in the array, so you can see exactly what each column holds:

Watch the grey part grow: every check throws away half of the columns that are left. That is why binary search is so fast.

Here is binary search in C. It prints every item it checks:

Example

#include <stdio.h>

// Returns the index of the value, or -1 if it is not found
int binarySearch(int arr[], int length, int value) {
  int low = 0;
  int high = length - 1;

  while (low <= high) {
    int middle = (low + high) / 2;
    printf("Checking index %d (value %d)\n", middle, arr[middle]);

    if (arr[middle] == value) {
      return middle;     // Found it
    } else if (arr[middle] < value) {
      low = middle + 1;  // Search the right half
    } else {
      high = middle - 1; // Search the left half
    }
  }

  return -1; // Not found
}

int main() {
  int numbers[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
  int length = sizeof(numbers) / sizeof(numbers[0]);

  int index = binarySearch(numbers, length, 23);

  if (index != -1) {
    printf("Found 23 at index %d\n", index);
  } else {
    printf("23 was not found\n");
  }

  return 0;
}

Result:

Checking index 4 (value 16)
Checking index 7 (value 56)
Checking index 5 (value 23)
Found 23 at index 5
Try it Yourself »

Example Explained

  • low and high mark the part of the array we still search. At the start, that is the whole array.
  • middle is the index in the middle of that part.
  • If the middle value is too small, we move low past the middle. If it is too big, we move high before the middle.
  • When low becomes bigger than high, there is nothing left to search, so the value is not in the array.


Linear Search vs. Binary Search

How many checks does each search need in the worst case?

Number of Items Linear Search Binary Search
1010 checks4 checks
100100 checks7 checks
1,0001,000 checks10 checks
1,000,0001,000,000 checks20 checks

Binary search is amazingly fast. Even with a million items, it needs only 20 checks!

And now the answer to the guessing game: the smartest first guess is 50, right in the middle. Then keep guessing the middle of what is left. That is binary search, and you will always find the number in 7 guesses or fewer.


Summary

  • Linear search checks every item, one by one. It works on any array.
  • Binary search checks the middle item and throws away half of the items at every step.
  • Binary search is much faster, but the array must be sorted.

Binary search needs sorted data. So how do you sort an array? That is the next chapter!


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.