-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortSquares.java
More file actions
46 lines (39 loc) · 1.09 KB
/
SortSquares.java
File metadata and controls
46 lines (39 loc) · 1.09 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
package Array;
import java.util.Arrays;
public class SortSquares {
/**
* @param a - It is the array which has -ve to +ve values.
* @return - It returns the ans array in which squares are sorted.
*/
static int[] sortedSquares(int[] a) {
int n = a.length, i = 0, j = n - 1, k = 0;
int[] ans = new int[n];
while (i <= j) {
if (Math.abs(a[i]) < Math.abs(a[j])) {
a[j] *= a[j];
ans[k++] = (a[j--]);
} else {
a[i] *= a[i];
ans[k++] = (a[i++]);
}
}
reverse(ans);
return ans;
}
static void reverse(int[] a) {
int temp, i = 0, j = a.length - 1;
while (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
// Time Complexity - O(n), Auxiliary Space - O(n)
public static void main(String[] args) {
int[] a = {-10, -3, 2, 5, 6};
int[] ans = sortedSquares(a);
System.out.println(Arrays.toString(ans));
}
}