# Three Number Sort ⇒ counting sort or radix sort ⇒ three pointer with in-place swap

![](/files/s6w9OVWhcUHkXhsolTeo)

* n x m, 1

```jsx
function threeNumberSort(arr, order) {

  let pointer = 0;
  for (const target of order) {
    
    for (let i = pointer; i < arr.length; i++) {
      const curr = arr[i];
      if (target !== curr) continue;
      swap(arr, pointer, i);
      pointer++;
    }
    
  }

  return arr;
}

function swap(arr, a, b) {
  [arr[b], arr[a]] = [arr[a], arr[b]];
  return arr;
}

// Do not edit the line below.
exports.threeNumberSort = threeNumberSort;
```

* faster?
* with only 3 numbers?
* three pointers
* n, 1

```jsx
function threeNumberSort(arr, order) {
  
  const pointers = [0, 0, 0];
  for (let i = 0; i < arr.length; i++) {
    
    const curr = arr[i];
    if (curr === order[0]) {
      pointers[0]++;
      pointers[1]++;
      pointers[2]++;
    } else if (curr === order[1]) {
      pointers[1]++;
      pointers[2]++;
    } else {
      pointers[2]++;
    }
    
  }

  for (let i = 0; i < arr.length; i++) {
    
    if (i < pointers[0]) {
      arr[i] = order[0];
    } else if (i < pointers[1]) {
      arr[i] = order[1];
    } else {
      arr[i] = order[2];
    }
    
  }

  return arr;
}

function swap(arr, a, b) {
  [arr[b], arr[a]] = [arr[a], arr[b]];
  return arr;
}

// Do not edit the line below.
exports.threeNumberSort = threeNumberSort;
```

* 3rd try
* iteration - in place swap

```jsx
function threeNumberSort(arr, order) {
  let f = 0;
  let s = 0;
  let e = arr.length - 1;
  while (s <= e) {
    const curr = arr[s];

    if (curr === order[0]) {

      swap(arr, f, s);
      f++;
      s++;
    } else if (curr === order[1]) {
      s++;
    } else {
      swap(arr, e, s);
      e--;
    }  
  }
  
  return arr;
}

function swap(arr, a, b) {
  [arr[a], arr[b]] = [arr[b], arr[a]];
  return arr;
}

// Do not edit the line below.
exports.threeNumberSort = threeNumberSort;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/three-number-sort-counting-sort-or-radix-sort-three-pointer-with-in-place-swap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
