Created
August 9, 2017 19:07
-
-
Save engtomhat/239cb18dea5abf16e95083e645aef4ee to your computer and use it in GitHub Desktop.
75. Sort Colors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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