- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquareArray.java
More file actions
Latest commit
44 lines (36 loc) · 994 Bytes
/
Copy pathSortedSquareArray.java
File metadata and controls
44 lines (36 loc) · 994 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
41
42
43
44
packagecom.sarvesh.javabasics;
importjava.util.Arrays;
importjava.util.Scanner;
publicclassSortedSquareArray {
publicstaticvoidmain (String[] args) {
Scannerscanner = newScanner(System.in);
System.out.println("Enter Number of Elemeents in array: ");
intn = scanner.nextInt();
int[] arr = newint[n];
System.out.println("Enter Array Elements: ");
for(inti = 0 ; i<n;i++) {
arr[i] = scanner.nextInt();
}
System.out.println("The sorted square array : " + Arrays.toString(Square(arr)));
}
publicstaticint[] Square(int[] arr) {
intleft = 0;
intright=arr.length-1;
intwriteindex = arr.length-1;
int[] result = newint[arr.length];
while(left<=right) {
intleftsquare= arr[left]*arr[left];
intrightsquare = arr[right]*arr[right];
if(leftsquare>rightsquare) {
result[writeindex] = leftsquare;
left++;
}
else {
result[writeindex] = rightsquare;
right--;
}
writeindex--;
}
returnresult;
}
}