I'm working on building an algorithm that sorts in place for an array of nondecreasing integers, and it's not passing some of my tests. I was wondering why? I've included a sample input and output as well.
import java.util.*;
class Program {
public int[] sortedSquaredArray(int[] array) {
int[] res = new int[array.length];
int leftPointer = 0;
int rightPointer = array.length - 1;
int counter = 0;
while (counter < array.length) {
int leftSquared = array[leftPointer] * array[leftPointer];
int rightSquared = array[rightPointer] * array[rightPointer];
if (leftSquared < rightSquared) {
res[counter] = leftSquared;
leftPointer++;
} else if (rightSquared <= leftSquared) {
res[counter] = rightSquared;
rightPointer--;
}
counter++;
}
return res;
}
}
"array": [-50, -13, -2, -1, 0, 0, 1, 1, 2, 3, 19, 20]
expected output:
[0, 0, 1, 1, 1, 4, 4, 9, 169, 361, 400, 2500]
what I'm getting:
[400, 361, 9, 4, 1, 1, 0, 0, 1, 4, 169, 2500]
in placemean additional space dominated by array size?