newLearner
newLearner

Reputation: 19

why array not sort properly in function

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

Upvotes: 0

Views: 123

Answers (1)

pebble unit
pebble unit

Reputation: 1182

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

Upvotes: 1

Related Questions