Sort Colors

Given an array with n objects colored red, white or blue, sort them 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.

Solution:

public class Solution {
    public void sortColors(int[] nums) {
        int start = 0;
        int end = nums.length-1;
        for(int i=0; i<=end; i++){
            while(nums[i]==2 && i<end) swap(nums, i, end--);
            while(nums[i]==0 && i>start) swap(nums, i, start++);
        }
    }
    public void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

Solution 1: merge sort

public class Solution {
    public void sortColors(int[] nums) {
        sortColors(nums, 0, nums.length-1);
    }
    public void sortColors(int[] nums, int lo, int hi) {
        if(lo>=hi) return;
        int mid=lo+(hi-lo)/2;
        sortColors(nums, lo, mid);
        sortColors(nums, mid+1, hi);
        int[] sorted = new int[hi-lo+1];
        for(int ii=0; ii<sorted.length; ii++) sorted[ii]=nums[lo+ii];
        int k=lo,i=0,j=(hi-lo)/2+1;
        while(i<=(hi-lo)/2 && j<sorted.length){
            if(sorted[i]<sorted[j])
                nums[k++] = sorted[i++];
            else
                nums[k++] = sorted[j++];
        }
        while(i<=(hi-lo)/2) nums[k++]=sorted[i++]; 
    }
}

Solution 2: quick sort

public class Solution {
    public void sortColors(int[] nums) {
        sortColors(nums, 0, nums.length-1);
    }
    public void sortColors(int[] nums, int lo, int hi) {
        if(lo>=hi) return;
        int l=lo+1, r=hi;
        while(l<=r){
            while(l<=r && nums[l]<nums[lo]) l++;
            while(l<=r && nums[r]>=nums[lo]) r--;
            if(l<r) swap(nums, l++, r--);
        }
        swap(nums, lo, r);
        sortColors(nums, lo, r-1);
        sortColors(nums, r+1, hi);
    }
    public void swap(int[] nums, int i, int j){
        int tmp = nums[j];
        nums[j] = nums[i];
        nums[i] = tmp;
    }
}
comments powered by Disqus