Pages

Wednesday, 7 June 2017

For the given position find the perfect square else make it to next nearest perfect square,then make that to first element and align remaining in ascending order

public class PerfectSquare {

public static void main(String[] args) {
int a[] = {3,12,61,22,78,7};
int sq=0,sqt=0,pos,fp,tmp;
Scanner s = new Scanner(System.in);
System.out.println("Enter the position :");
pos = s.nextInt();
        
/*Making perfect square*/
while(sq != a[pos]){  
        sqt =(int) Math.sqrt(a[pos]);
        sq  = sqt * sqt;
       
        if(sq!=a[pos])
          a[pos]++;
        }

/*Swapping perfect square element to first position*/
fp=a[0];
a[0]=a[pos];
a[pos]=fp;

/*Sorting elements in ascending order - Bubble sort*/
for(int j=0;j<a.length;j++){
for(int k=0;k<a.length;k++){
if(j==0 || k==0)
continue;
if(a[k]>a[j]){
tmp  = a[k];
a[k] = a[j];
a[j] = tmp;
}
}
}

for(int i:a){
System.out.print(i+" ");
}
s.close();
}
}

Output:

Enter the position :
3

25 3 7 12 61 78 

No comments:

Post a Comment

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...