# Read the first n items of several sorted lists

> Merge sorted inputs lazily, and stop as soon as you have enough.

**Few items**

```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'

const shards = [
  [1, 4, 9, 12],
  [2, 3, 10],
  [5, 6, 7, 8],
]

const firstFive: number[] = []

for (const id of mergeSorted(numberOrder, shards)) {
  firstFive.push(id)

  if (firstFive.length === 5) {
    break // closes every shard; the rest is never read
  }
}

firstFive // [1, 2, 3, 4, 5]
```

**Thousands of items**

```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'

let reads = 0

// 16 shards holding the ids 0 to 65,535 between them, each shard already sorted.
function* shard(index: number): Generator<number> {
  for (let offset = 0; offset < 4_096; offset += 1) {
    reads += 1
    yield index + offset * 16
  }
}

const shards = Array.from({ length: 16 }, (_, index) => shard(index))

const page: number[] = []

for (const id of mergeSorted(numberOrder, shards)) {
  page.push(id)

  if (page.length === 32) {
    break // closes every shard
  }
}

page.length // 32
page.at(-1) // 31, the last id a 32-row page needs
reads // 47, out of the 65,536 ids the shards hold
```

The merge reads one item per input to start, then only from the input it last took from. Breaking out of the loop closes every input, so a page of results costs the page, not the whole input.

**Modules:** [`knotkit/sorted-merge`](/modules/sorted-merge/) · [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/sorted-merge/)
