Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array after converting to squares

class Solution {
    public int[] sortedSquares(int[] arr) {
        for(int i = 0; i < arr.length; i++){
            for(int j=i+1;j<arr.length;j++){
                arr[i]=arr[i]*arr[i];
                arr[j]=arr[j]*arr[j];
                if(arr[j]<arr[i]){
                    int temp=0;
                    temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                    
                    
                }
            }
        }
        return arr;
}
}

can you tell me where am going wrong.. for input [-4,-1,0,3,10] output should be [0,1,9,16,100] , My current output is [0,1,43046721,0,1874919424] .. I don’t want to use Array.sort() . Wanted to write own code.. can you help me in fixing this and where am going wrong. Thanks in advance

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your sort loop is functional but you are squaring each entry 4 times in a cumulative manner. One approach is to first square all the elements and then sort.

From your results you can see evidence:

(((3^2)^2)^2)^2 = 43046721

The second 0 is interesting:

(((-4^2)^2)^2)^2 = 4,294,967,296

which for a 32-bit int becomes 0.

And for 10:

(((10^2)^2)^2)^2 = 10,000,000,000,000,000

rolls over to 187491924.

So your code can simply be updated by first squaring the entries and then sort:

public int[] sortedSquares(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i] * arr[i];
    }
    for(int i = 0; i < arr.length; i++){
        for(int j=i+1;j<arr.length;j++){
            if(arr[j]<arr[i]){
                int temp=0;
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
    return arr;
}    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading