-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDutchNationalFlagTwo.java
More file actions
37 lines (32 loc) · 990 Bytes
/
DutchNationalFlagTwo.java
File metadata and controls
37 lines (32 loc) · 990 Bytes
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
package swe;
import java.util.Arrays;
public class DutchNationalFlagTwo {
public static int[] sortedArray(int[] nums) {
int left = 0;
int mid = 0;
int right = 0;
while (mid <= right) {
if (nums[mid] == 0) {
swap(nums, mid, left);
mid++;
left++;
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums, mid, right);
right--;
}
}
return nums;
}
public static void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
public static void main(String[] args) {
int[] nums = {0, 1, 2, 1, 2, 2, 2, 1, 0};
System.out.println("Input: " + Arrays.toString(nums));
System.out.println("Output: " + Arrays.toString(sortedArray(nums)));
}
}