-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortColors.java
More file actions
49 lines (44 loc) · 1.08 KB
/
SortColors.java
File metadata and controls
49 lines (44 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package Leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class SortColors
{
public static void main( String[] args )
{
SortColors sortColors = new SortColors();
int[] nums = new int[]{ 2, 0, 1 };
sortColors.sortColor( nums );
System.out.println( Arrays.toString( nums ) );
}
public void sortColor( int[] nums )
{
int low = 0;
int mid = 0;
int high = nums.length - 1;
while( mid <= high )
{
switch( nums[mid] )
{
case 0:
swap( nums, low, mid );
low++;
mid++;
break;
case 1:
mid++;
break;
case 2:
swap( nums, mid, high );
high--;
}
}
}
private void swap( int[] nums, int i, int j )
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}