AlgoTales · Roadmap

Searching unsorted data

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

When data has no order, the only sure way to find all matches is to look at every item once. This is what filters, log searches and array_filter do. It is fine for moderate data, and it explains why people prepare data before searching on big sets.

Practical use cases

  • Web app: Product filters on a listing page. A shopper ticks "Brand: Sony" and "Under Rs 5,000". The code walks through the products and keeps those that match both conditions. With 500 products it is instant, but with 5 lakh the page needs a database index or a prepared structure.
  • Web app: Filtering a to-do list. A task app lets you type in a box and shows only tasks containing those words. The front end goes through every task on each keystroke. With 300 tasks the typing stays smooth, so no special data structure is needed at that size.
  • System: Searching server logs. Log files are written in time order, not by error type. To find every line containing "timeout", a tool like grep reads the entire file from start to finish. That is why very large logs are loaded into a search engine instead.

The story: The Mess in the School Bag

Kabir's school bag looked like a tornado had visited it. Worksheets, a half-eaten biscuit, test papers, all mixed up in no order at all. Mrs. Sharma said, "Bring me every paper that has the number 3 on top."

Kabir thought about the binary search trick Mira had shown him. "I will open the middle and decide which half to throw away!" But the first middle paper said 7. Was 3 to the left or to the right? He had no idea. In a messy pile, a 7 tells you nothing about where a 3 is hiding.

So he did the honest thing: he picked up every paper, one by one, kept the 3s aside, and did not stop early, because there could be more. That is searching unsorted data. With no order to lean on, you must look at everything. Sorting the pile first costs more work, so if you only search once, just scan. If you will search many times, sorting first can pay off.

How to spot this problem, and where you need it

Your data is in no useful order and you need every item that meets a condition. You must decide whether looking at everything is acceptable or whether you must organise the data first.

Signs you need it

  • You use array_filter, filter(), a WHERE clause on a column with no index, or grep to find items that match a condition.
  • The search is on a field such as "contains this text" or "any of these conditions", where no simple ordering helps.
  • The page is fine with test data but slows down visibly when the table reaches hundreds of thousands of rows.

Where to use it in a project

  • Filter panels on shop and job listing pages, and search boxes on small lists.
  • Log viewers, admin tools and one-off reports on data that nobody has indexed.

The solution

Go through every item once and keep the ones that pass your test. That is correct and simple, and it is the right answer for small or one-time jobs. If the same search repeats often on a big set, prepare the data first: add a database index, sort it, or build a map from the field to the items. Then each search stops reading everything.

Payoff: Before: every filter click reads 5 lakh rows and takes seconds. After an index: it reads only matching rows and answers in milliseconds.

Explain it like I am 8

If your toys are thrown in one big box, the only way to find all your red cars is to pick up every single toy and check. If the toys were lined up by colour, you could jump straight to the red part. Messy box: check everything.

How it works, step by step

  1. Accept the mess: there is no order, so no shortcut like "halving" is allowed.
  2. Walk the list once from the first item to the last.
  3. For each item ask your question: equal to the target? bigger than 8? starts with "A"? Any yes/no test works.
  4. Collect every position that answers yes. If you only need the first match, stop at it. If you need all matches, finish the walk.

The code in four languages

PHP

<?php
// All positions where the value equals $target (works on any order).
function findAll(array $items, int $target): array {
    $found = [];
    foreach ($items as $i => $value) {
        if ($value === $target) {
            $found[] = $i;               // remember it, keep scanning
        }
    }
    return $found;
}

// First item that passes any yes/no test (a "condition").
function findFirst(array $items, callable $test): int {
    foreach ($items as $i => $value) {
        if ($test($value)) {
            return $i;                   // first one is enough
        }
    }
    return -1;
}

$pile = [7, 3, 9, 3, 5, 3, 8];
echo implode(',', findAll($pile, 3)), "\n";          // 1,3,5
echo findFirst($pile, fn($x) => $x > 8), "\n";        // 2 (the 9)

JavaScript

// All positions where the value equals target (works on any order).
function findAll(items, target) {
  const found = [];
  for (let i = 0; i < items.length; i++) {
    if (items[i] === target) {
      found.push(i);                  // remember it, keep scanning
    }
  }
  return found;
}

// First item that passes any yes/no test (a "condition").
function findFirst(items, test) {
  for (let i = 0; i < items.length; i++) {
    if (test(items[i])) {
      return i;                       // first one is enough
    }
  }
  return -1;
}

const pile = [7, 3, 9, 3, 5, 3, 8];
console.log(findAll(pile, 3).join(','));            // 1,3,5
console.log(findFirst(pile, x => x > 8));           // 2 (the 9)

Java

import java.util.*;
import java.util.function.IntPredicate;

public class Main {
    // All positions where the value equals target (works on any order).
    static List<Integer> findAll(int[] items, int target) {
        List<Integer> found = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            if (items[i] == target) {
                found.add(i);                  // remember it, keep scanning
            }
        }
        return found;
    }

    // First item that passes any yes/no test (a "condition").
    static int findFirst(int[] items, IntPredicate test) {
        for (int i = 0; i < items.length; i++) {
            if (test.test(items[i])) {
                return i;                      // first one is enough
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] pile = {7, 3, 9, 3, 5, 3, 8};
        System.out.println(findAll(pile, 3).toString().replaceAll("[\\[\\] ]", ""));   // 1,3,5
        System.out.println(findFirst(pile, x -> x > 8));                                // 2 (the 9)
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// findAll returns all positions where the value equals target (works on any order).
func findAll(items []int, target int) []int {
	var found []int
	for i, value := range items {
		if value == target {
			found = append(found, i) // remember it, keep scanning
		}
	}
	return found
}

// findFirst returns the first item that passes any yes/no test (a "condition").
func findFirst(items []int, test func(int) bool) int {
	for i, value := range items {
		if test(value) {
			return i // first one is enough
		}
	}
	return -1
}

func main() {
	pile := []int{7, 3, 9, 3, 5, 3, 8}
	var parts []string
	for _, i := range findAll(pile, 3) {
		parts = append(parts, strconv.Itoa(i))
	}
	fmt.Println(strings.Join(parts, ","))                           // 1,3,5
	fmt.Println(findFirst(pile, func(x int) bool { return x > 8 })) // 2 (the 9)
}

Time: O(n) · Extra space: O(k). You read all n items once; you store the k positions you found (O(1) if you only return the first).

Watch out for

  • Trying binary search on unsorted data. It will happily return a wrong "not found".
  • Stopping at the first match when the question was "find all".
  • Sorting a big list just to search it once. Sorting costs more than one scan.

Quick check

  1. Why can we not halve an unsorted list?
    • One item tells us nothing about where the others are
    • It is too long
    • Computers cannot compare numbers
  2. To collect every match in unsorted data you must...
    • Stop at the first match
    • Sort first, always
    • Read every item
  3. You will search the same big list 1,000 times. A good idea is to...
    • Sort it once, then use faster searches
    • Scan it every time
    • Delete half of it