Skip to content

Instantly share code, notes, and snippets.

@engtomhat
Created August 9, 2017 19:07
Show Gist options
  • Save engtomhat/239cb18dea5abf16e95083e645aef4ee to your computer and use it in GitHub Desktop.
Save engtomhat/239cb18dea5abf16e95083e645aef4ee to your computer and use it in GitHub Desktop.
75. Sort Colors
public class SortColors {
public void sortColors(int[] nums) {
if(nums.length > 1) {
int redIndex = 0;
int blueIndex = nums.length-1;
int i = 0;
while(i <= blueIndex) {
if(nums[i] == 2) {
// Send blue node to end of array
swap(nums, i, blueIndex--);
// Do not proceed to next node, need to check new value for red
} else if(nums[i] == 0) {
// Send red to beginning of array
swap(nums, i, redIndex++);
i++;
} else {
i++;
}
}
}
}
private void swap(int[] nums, int index, int swapIndex) {
int temp = nums[swapIndex];
nums[swapIndex] = nums[index];
nums[index] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment