Skip to main content

Command Palette

Search for a command to run...

sort 0 1 2

Published
1 min readView as Markdown
class Solution {
    public void sortColors(int[] nums) {
        int low = 0, mid = 0, high = nums.length - 1;

        while (mid <= high) {
            if (nums[mid] == 0) {
                // Swap with low and move both pointers forward
                swap(nums, low, mid);
                low++;
                mid++;
            } else if (nums[mid] == 1) {
                // Leave 1 in place and move mid forward
                mid++;
            } else {
                // nums[mid] == 2, swap with high and move high backward
                swap(nums, mid, high);
                high--;
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

More from this blog

Amit singh's blog

235 posts