Home > front end >  Sort array after converting to squares
Sort array after converting to squares

Time:09-09

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

CodePudding user response:

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;
}    
  • Related