Sort Colors

Monisha Mathew
1 min readApr 19, 2019

--

Question: Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

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

Note: You are not suppose to use the library’s sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

You may view the full question here.

Approach 1: In place sorting! Well here is an attempt —

//Approach 1:
//Runtime: 0ms
//Memory usage: 37.1MB
class Solution {
public void sortColors(int[] nums) {
int start = 0;
int i = 0;
int end = nums.length-1;
int temp;
while(i<=end){
if(nums[i]==2){
temp = nums[end];
nums[end] = nums[i];
nums[i] = temp;
end--;
} else if(nums[i]==1){
i++;
} else if(nums[i]==0){
temp = nums[start];
nums[start] = nums[i];
nums[i] = temp;
start++;
i++;
}
}
}
}

Find more posts here.

Cheers & Chao!

--

--