Skip to content

Commit 0cd049f

Browse files
committed
Add SortedSquareInNonDecreasingOrder class to sort and square elements of a non-decreasing array
1 parent c4241b0 commit 0cd049f

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.*;
2+
3+
public class SortedSquareInNonDecreasingOrder {
4+
5+
static int printArray(int[] arr){
6+
for(int i=0; i<arr.length; i++){
7+
System.out.print(arr[i]+" ");
8+
}
9+
return 0;
10+
}
11+
12+
static void swapInArray(int[] arr, int i, int j){
13+
int temp=arr[i];
14+
arr[i]=arr[j];
15+
arr[j]=temp;
16+
}
17+
18+
static void reverse(int[] arr){
19+
int i=0;
20+
int j=arr.length-1;
21+
while(i<j){
22+
swapInArray(arr, i, j);
23+
i++;
24+
j--;
25+
}
26+
}
27+
28+
static int[] sortSquare(int[] arr){
29+
int n=arr.length;
30+
int left=0;
31+
int right=n-1;
32+
33+
int[] ans=new int[n];
34+
int k=0;
35+
36+
while(left <= right){
37+
if(Math.abs(arr[left]) > Math.abs(arr[right]) ){
38+
ans[k++]= arr[left] * arr[left];
39+
left++;
40+
}else{
41+
ans[k++]= arr[right] * arr[right];
42+
right--;
43+
}
44+
}
45+
return ans;
46+
}
47+
48+
49+
public static void main(String[] args) {
50+
Scanner sc=new Scanner(System.in);
51+
52+
System.out.print("Enter the size of array: ");
53+
int n=sc.nextInt();
54+
55+
int[] arr= new int[n];
56+
57+
System.out.print("Enter the "+ n + " Elements(non-decreasing order): ");
58+
59+
for(int i=0; i<arr.length; i++){
60+
arr[i]=sc.nextInt();
61+
}
62+
63+
System.out.print("Original Array: ");
64+
printArray(arr);
65+
66+
System.out.println();
67+
68+
int[] ans=sortSquare(arr);
69+
reverse(ans);
70+
System.out.print("After Square in order of non-decrersing: ");
71+
printArray(ans);
72+
73+
74+
}
75+
}

0 commit comments

Comments
 (0)