0

enter image description here

public int[] sortedSquares(int[] nums) {
    int size = nums.length;
    int result[] = new int[size];
    
    for(int i=0; i<size-1; i++)
    {
        int min =i;
        for(int j=i+1; j<size; j++)
        
            if(nums[j]<nums[min])
            
                min = j;        
                int temp = nums[min];
                nums[min] = nums[i];
                nums[i]=temp;
        
    
    }
      for(int i=0; i<size; i++)
      {
          result[i] = nums[i]*nums[i];
      }
    
    return result;
    
}

this is from leetcode question "Squares of a Sorted Array" I sorted it and the result come out not sort. i dont know what happen? if i use Arrays.sort(result) it will work, but why this code not working?

enter image description here

9
  • i try it not work,, Commented Jan 8, 2022 at 8:06
  • yes, but it work for the void function Commented Jan 8, 2022 at 8:09
  • so i made void sort(int arr[]) function it is correct, but it does not work with return int sortSquare[]; Commented Jan 8, 2022 at 8:13
  • 1
    NO¹, you need to sort AFTER squaring (@expeeriment code is correct, indentation is wrong - only min = j must be inside if and for, swaping should be done after the loop - the code with black background is correctly indented) ¹ you can use abs before sorting, but that will make code even harder to understand, and no need, just sort after squaring (squares should sorted, so sort the squares {if input should be squared then sort the input}) Commented Jan 8, 2022 at 8:21
  • 1
    actually code on right pane (black background) is also badly indented, just less bad than the one on the left - please get used to ALWAYS use {} for if, else, for, while, ... and let the IDE indent your code (if you don't want to do it) Commented Jan 8, 2022 at 8:27

1 Answer 1

1

i didnt catch what @user16320675 mentioned about the squaring after sorting at first glance, but yeah he is right. This should give the output you want.

 public int[] sortedSquares(int[] nums) {
    int size = nums.length;
    int result[] = new int[size];

    for(int i=0; i<size; i++)
    {
        result[i] = nums[i]*nums[i]; //square items
    }

    for(int i=0; i<size-1; i++) {
        int min = i;
        for (int j = i + 1; j < size; j++) { //sort squared items
            if (result[j] < result[min]) {
                min = j;
            }
        }

        int temp = result[min];
        result[min] = result[i];
        result[i] = temp;

    }

    return result;

}

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

it... passes the test case you were asking for...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.