Searching & Sorting Security Data

15 min In Progress

Learning Objectives

  • Compare linear vs binary search — know when to use each
  • Sort log entries by severity using sorted() and a key function
  • Apply these patterns to real security data

Linear vs Binary Search

Linear search checks every item — O(n), works on anything. Binary search halves the list each time — O(log n), but requires a sorted list. Searching a blocklist of 1 million IPs: linear = up to 1,000,000 checks, binary = at most 20 checks.

# Linear — O(n)
def linear_search(ip_list, target):
    for ip in ip_list:
        if ip == target:
            return True
    return False

# Binary — O(log n), list must be sorted
def binary_search(ip_list, target):
    low, high = 0, len(ip_list) - 1
    while low <= high:
        mid = (low + high) // 2
        if ip_list[mid] == target:
            return True
        elif ip_list[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return False

blocklist = ["10.0.0.1", "10.0.0.5", "192.168.1.99"]
print(binary_search(sorted(blocklist), "10.0.0.5"))

Sorting Logs by Severity

Raw logs are chronological. For forensics you want them sorted by severity, IP, or event type. Python's sorted() with a key= function does this in one line.

logs = [
    {"ip": "10.0.0.3", "severity": 3, "event": "port scan"},
    {"ip": "10.0.0.1", "severity": 9, "event": "brute force"},
    {"ip": "10.0.0.2", "severity": 1, "event": "ping"},
]

by_severity = sorted(logs, key=lambda x: x["severity"], reverse=True)

for log in by_severity:
    print(f"[{log['severity']}] {log['ip']} — {log['event']}")

📝 Exercise: Blocklist Lookup

Given a sorted list of blocked IPs, use binary_search to check if '10.0.0.7' and '172.16.0.1' are blocked. Print BLOCKED or ALLOWED for each.

code.py
Output

            
← Back to Chapter