-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquares.java
More file actions
40 lines (27 loc) · 851 Bytes
/
SortedSquares.java
File metadata and controls
40 lines (27 loc) · 851 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
38
39
40
import java.util.Arrays;
class SortedSquares {
public int[] sortedSquares(int[] nums) {
int arr[] = new int[nums.length];
// square store in new array
for(int i = 0; i < nums.length; i++){
arr[i] = nums[i] * nums[i];
}
// insertion sort
for(int i = 1; i < arr.length; i++){
int curr = arr[i];
int prev = i - 1;
while(prev >= 0 && arr[prev] > curr){
arr[prev + 1] = arr[prev];
prev--;
}
arr[prev + 1] = curr;
}
return arr;
}
public static void main(String[] args) {
int nums[] = {-4,-1,0,2,3};
SortedSquares obj = new SortedSquares();
int result[] = obj.sortedSquares(nums);
System.out.println(Arrays.toString(result));
}
}