-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquareArray.java
More file actions
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
package com.sarvesh.javabasics;
import java.util.Arrays;
import java.util.Scanner;
public class SortedSquareArray {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number of Elemeents in array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter Array Elements: ");
for(int i = 0 ; i<n;i++) {
arr[i] = scanner.nextInt();
}
System.out.println("The sorted square array : " + Arrays.toString(Square(arr)));
}
public static int[] Square(int[] arr) {
int left = 0;
int right=arr.length-1;
int writeindex = arr.length-1;
int[] result = new int[arr.length];
while(left<=right) {
int leftsquare= arr[left]*arr[left];
int rightsquare = arr[right]*arr[right];
if(leftsquare>rightsquare) {
result[writeindex] = leftsquare;
left++;
}
else {
result[writeindex] = rightsquare;
right--;
}
writeindex--;
}
return result;
}
}