Skip to content

Commit f8db2fb

Browse files
authored
Create SortedSquares.java
1 parent db5f7f0 commit f8db2fb

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

LeetCode/SortedSquares.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
// Java program to Sort square of the numbers
3+
// of the array
4+
import java.util.*;
5+
import java.io.*;
6+
7+
public class sortsq
8+
{
9+
// Function to sort an square array
10+
public static void sortSquares(int arr[])
11+
{
12+
int n = arr.length;
13+
14+
// First convert each array elements
15+
// into its square
16+
for (int i = 0 ; i < n ; i++)
17+
arr[i] = arr[i] * arr[i];
18+
19+
// Sort an array using "inbuild sort function"
20+
// in Arrays class.
21+
Arrays.sort(arr);
22+
}
23+
24+
// Driver program to test above function
25+
public static void main (String[] args)
26+
{
27+
int arr[] = { -6 , -3 , -1 , 2 , 4 , 5 };
28+
int n = arr.length;
29+
30+
System.out.println("Before sort ");
31+
for (int i = 0; i < n; i++)
32+
System.out.print(arr[i] + " ");
33+
34+
sortSquares(arr);
35+
System.out.println("");
36+
System.out.println("After Sort ");
37+
for (int i = 0 ; i < n ; i++)
38+
System.out.print(arr[i] + " ");
39+
40+
}
41+
}

0 commit comments

Comments
 (0)