Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created June 20, 2013 03:18
Show Gist options
  • Select an option

  • Save luoxiaoxun/5820065 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5820065 to your computer and use it in GitHub Desktop.
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. Note: You are not suppose to use the library's sort function for this problem. F…
C++:
class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int head=0;
int tail=n-1;
int cur=0;
while(cur<=tail){
if(A[cur]==0){
if(cur>head) swap(A,head,cur);
head++;
cur++;
}else if(A[cur]==2){
swap(A,cur,tail);
tail--;
}else if(A[cur]==1) cur++;
}
}
void swap(int *A,int i,int j){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
};
Java:
public class Solution {
public void sortColors(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int head=0;
int tail=A.length-1;
int cur=0;
while(cur<=tail){
if(A[cur]==0){
if(cur>head) swap(A,head,cur);
head++;
cur++;
}else if(A[cur]==2){
swap(A,cur,tail);
tail--;
}else if(A[cur]==1) cur++;
}
}
public void swap(int[] A,int i,int j){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment