-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
55 lines (47 loc) · 1.12 KB
/
solution.java
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
47
48
49
50
51
52
53
54
55
// Java program to Sort square of
// the numbers of the array
import java.util.*;
import java.io.*;
class GFG{
// Function to sort an square array
public static void sortSquares(int arr[])
{
int n = arr.length, left = 0,
right = n - 1;
int result[] = new int[n];
for(int index = n - 1; index >= 0; index--)
{
if (Math.abs(arr[left]) > arr[right])
{
result[index] = arr[left] * arr[left];
left++;
}
else
{
result[index] = arr[right] * arr[right];
right--;
}
}
for(int i = 0; i < n; i++)
arr[i] = result[i];
}
// Driver code
public static void main(String[] args)
{
int arr[] = { -6, -3, -1, 2, 4, 5 };
int n = arr.length;
System.out.println("Before sort ");
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
sortSquares(arr);
System.out.println("");
System.out.println("After Sort ");
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
/* Output:
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36 */