Here we sort an element by taking the squares of the element. That is nothing but the each and every number in an given array is squared and then sorted (in ascending order). This can be clearly explined with an example:
Input: 1,3,2,5,0
Output: 0,1,4,9,25
Here first the elements are squared and then sorted with respect to the obtained values.
The source code for the above explanation is given below:
{
public static void main(String[] args)
{
int[] a={-7,-3,-1,4,8,12};
int t,n=a.length;
for(int i=0;i<n;i++)
a[i]=square(a[i]);
for(int i=0;i<n-1;i++)
{
for(int j=i;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
for(int i=0;i<n;i++)
System.out.print(a[i]+"\t");
}
static int square(int n)
{
return n*n;
}
}
Initially an array is taken and the array of elements are stored in an variable 'a', next a temporary variable 't' and to store the length of the element variable 'n' ( the variable_name.length gives the length of the particular variable ). The all the elements in the array are then squared with the help of function square(). The sorting of an array is done by applying the logic of sorting the numbers and then the output is displayed on the display screen.
Input: 1,3,2,5,0
Output: 0,1,4,9,25
Here first the elements are squared and then sorted with respect to the obtained values.
The source code for the above explanation is given below:
Program:
public class Main{
public static void main(String[] args)
{
int[] a={-7,-3,-1,4,8,12};
int t,n=a.length;
for(int i=0;i<n;i++)
a[i]=square(a[i]);
for(int i=0;i<n-1;i++)
{
for(int j=i;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
for(int i=0;i<n;i++)
System.out.print(a[i]+"\t");
}
static int square(int n)
{
return n*n;
}
}
Output:
1 9 16 49 64 144Initially an array is taken and the array of elements are stored in an variable 'a', next a temporary variable 't' and to store the length of the element variable 'n' ( the variable_name.length gives the length of the particular variable ). The all the elements in the array are then squared with the help of function square(). The sorting of an array is done by applying the logic of sorting the numbers and then the output is displayed on the display screen.

0 Comments