public static void main(String[] args) {
int[] array = {-4, -1, 0, 3, 10};
int[] ints = sortedSquares(array);
System.out.println(Arrays.toString(ints));
}
public static int[] sortedSquares(int[] array) {
if (array == null) return null;
int[] ints = new int[array.length];
for (int i = 0; i < array.length; i++) {
int pow = (int) Math.pow(array[i], 2);
array[i] = pow;
}
//1,2,3,4,5
//0,1,2,3,4
int t = 0;
for (int k = array.length - 1; k >= 0; k--) {
int max = 0;//假设最大的索引
for (int j = 1; j <= k; j++) {
if (array[max] >= array[j]) {
max = j;
}
}
int tmp = array[max];
array[max] = array[k];
array[k] = tmp;
ints[t++] = array[k];
}
// System.out.println(Arrays.toString(ints));
return ints;
}
先求平方
在选择排序