codementor on Nostr: Learn: Linear search What: check the items one by one until you find the target. ...
Learn: Linear search
What: check the items one by one until you find the target.
Cost: O(n) in the worst case, O(1) extra memory.
Use it when: the data is not sorted, is small, or you search only once. Sorting first costs O(n log n), more than one linear search.
```csharp
int[] a = { 7, 3, 9, 1 };
Console.WriteLine(Array.IndexOf(a, 9));
Console.WriteLine(Array.IndexOf(a, 5));
```
It prints 2, then -1 (not found). Array.IndexOf and List<T>.Contains are linear searches.
Read more:
https://www.geeksforgeeks.org/dsa/linear-search/#tip · TIP-033
Published at
2026-10-13 18:37:58 UTCEvent JSON
{
"id": "33c7c9520fe149300376bb178fc35b85fe8192ccf861634b6989c93d92a575e2",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1791916678,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Linear search\n\nWhat: check the items one by one until you find the target.\nCost: O(n) in the worst case, O(1) extra memory.\nUse it when: the data is not sorted, is small, or you search only once. Sorting first costs O(n log n), more than one linear search.\n\n```csharp\nint[] a = { 7, 3, 9, 1 };\nConsole.WriteLine(Array.IndexOf(a, 9));\nConsole.WriteLine(Array.IndexOf(a, 5));\n```\n\nIt prints 2, then -1 (not found). Array.IndexOf and List\u003cT\u003e.Contains are linear searches.\n\nRead more: https://www.geeksforgeeks.org/dsa/linear-search/\n\n#tip · TIP-033",
"sig": "bdaf37a6a508ac4d2d04b4a44bafb131652b730b0a3a7f18de62727c17cd9f0f405f2e0af0d5f5f10241408a2cca3a5d5a33459760261d9fec3cd12898d7b38f"
}