# Leetcode Sort-Colors

#### 2022-09-01 13:24

> ##### Algorithms:
>
> #algorithm #two_pointers
>
> ##### Data structures:
>
> #DS #array
>
> ##### Difficulty:
>
> #coding_problems #difficulty_medium
>
> ##### Additional tags:
>
> #leetcode
>
> ##### Revisions:
>
> N/A

##### Links:

- [Link to problem](https://leetcode.com/problems/sort-colors/)

  ***

### Problem

Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

#### Examples

**Example 1:**

**Input:** nums = [2,0,2,1,1,0]
**Output:** [0,0,1,1,2,2]

**Example 2:**

**Input:** nums = [2,0,1]
**Output:** [0,1,2]

#### Constraints

- `n == nums.length`
- `1 <= n <= 300`
- `nums[i]` is either `0`, `1`, or `2`.

### Thoughts

> [!summary]
> This is a variant of double pointer method.

Simple double pointer method, check for cur and pointers to
avoid infinite loops.

### Solution

```cpp
class Solution {
public:
void sortColors(vector<int> &nums) {
  // Double pointer
  int lowptr = 0;
  int highptr = nums.size() - 1;
  int cur = 0;

  for (int size = nums.size(); cur < size; cur++) {
    if (nums[cur] == 0 && cur != lowptr) {
      swap(nums[lowptr++], nums[cur]);
      cur--;
    } else if (nums[cur] == 2 && cur < highptr) {
      swap(nums[highptr--], nums[cur]);
      cur--;
    }
  }
}
};
```
