-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinimumWindowSort.java
More file actions
39 lines (32 loc) · 1.53 KB
/
MinimumWindowSort.java
File metadata and controls
39 lines (32 loc) · 1.53 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
class ShortestWindowSort {
public static int sort(int[] arr) {
int low = 0, high = arr.length - 1;
// find the first number out of sorting order from the beginning
while (low < arr.length - 1 && arr[low] <= arr[low + 1])
low++;
if (low == arr.length - 1) // if the array is sorted
return 0;
// find the first number out of sorting order from the end
while (high > 0 && arr[high] >= arr[high - 1])
high--;
// find the maximum and minimum of the subarray
int subarrayMax = Integer.MIN_VALUE, subarrayMin = Integer.MAX_VALUE;
for (int k = low; k <= high; k++) {
subarrayMax = Math.max(subarrayMax, arr[k]);
subarrayMin = Math.min(subarrayMin, arr[k]);
}
// extend the subarray to include any number which is bigger than the minimum of the subarray
while (low > 0 && arr[low - 1] > subarrayMin)
low--;
// extend the subarray to include any number which is smaller than the maximum of the subarray
while (high < arr.length - 1 && arr[high + 1] < subarrayMax)
high++;
return high - low + 1;
}
public static void main(String[] args) {
System.out.println(ShortestWindowSort.sort(new int[] { 1, 11, 3, 0, 2, -2, 12 }));
System.out.println(ShortestWindowSort.sort(new int[] { 1, 3, 2, 0, -1, 7, 10 }));
System.out.println(ShortestWindowSort.sort(new int[] { 1, 2, 3 }));
System.out.println(ShortestWindowSort.sort(new int[] { 3, 2, 1 }));
}
}