Sum*_*ppi 8 java arrays sorting
我需要按升序对数组进行排序,仅用于正值.对于负值,指数位置将保持不变.
如果数组是:int[] inputArray = {-1, 150, 190, 170, -1, -1, 160, 180}
.
输出应该是这样的 - int[] outputArray = {-1, 150, 160, 170, -1, -1, 180, 190}
.
但就我而言,输出就是这个 - int[] outputArray = {-1, 150, 170, 190, -1, -1, 160, 180}
.
这是我的代码如下:
public static void main(String[] args) {
int[] inputArray = {-1, 150, 190, 170, -1, -1, 160, 180};
int[] outputArray = sortByHeight(inputArray);
for (int item : outputArray) {
System.out.print(item + ", ");
}
}
public static int[] sortByHeight(int[] inputArray) {
for (int i=0; i<inputArray.length; i++) {
for (int j = 0; j<inputArray.length - 1; j++) {
int temp = inputArray[j];
if (temp >= 0) {
if (inputArray[j] > inputArray[j+1] && inputArray[j+1] >= 0) {
inputArray[j] = inputArray[j+1];
inputArray[j+1] = temp;
}
}
}
}
return inputArray;
}
Run Code Online (Sandbox Code Playgroud)
在第二个循环中,inputArray[j]
您需要在比较之前找到大于0的下一个元素.
public static void main(String[] args) {
int[] inputArray = {-1, 150, 190, 170, -1, -1, 160, 180};
int[] outputArray = sortByHeight(inputArray);
for (int item : outputArray) {
System.out.print(item + ", ");
}
}
public static int[] sortByHeight(int[] inputArray) {
for (int i=0; i<inputArray.length; i++) {
for (int j = 0; j<inputArray.length - 1; j++) {
int temp = inputArray[j];
if (temp >= 0) {
int k = j+1;
while(inputArray[k] < 0)
k++;
if (inputArray[j] > inputArray[k] && inputArray[k] >= 0) {
inputArray[j] = inputArray[k];
inputArray[k] = temp;
}
}
}
}
return inputArray;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试对自己进行排序,或者只提取正值并对它们进行排序,但这里是一个备用版本,它使输入数组保持不变 (因为从方法返回新数组是不必要的).
代码只是首先复制和排序输入数组,然后将输入数组中的负值与排序数组中的正值合并.由于负值首先排序,因此不可能覆盖排序值作为副本.
代码也不会封装值,否则将构建List<Integer>
正值.
private static int[] sortByHeight(int[] inputArray) {
int[] arr = inputArray.clone();
Arrays.sort(arr);
int i = 0;
while (i < arr.length && arr[i] < 0)
i++;
for (int j = 0; j < arr.length; j++)
arr[j] = (inputArray[j] < 0 ? inputArray[j] : arr[i++]);
return arr;
}
Run Code Online (Sandbox Code Playgroud)
测试
int[] inputArray = {-1, 150, 190, 170, -2, -1, 160, 180};
int[] outputArray = sortByHeight(inputArray);
System.out.println(Arrays.toString(outputArray));
Run Code Online (Sandbox Code Playgroud)
产量
[-1, 150, 160, 170, -2, -1, 180, 190]
Run Code Online (Sandbox Code Playgroud)
重复使用arr
所有值的排序数组和结果数组,因为正值只会被复制下来,或者保持原样.
为了显示:
-1, 150, 190, 170, -2, -1, 160, 180 // Input array
? ? ?
? ? ?
? ? ?
-1, 150, 160, 170, -2, -1, 180, 190 // Result array
? ? ??????????? ? ?
? ??????????? ? ? ?
??????????? ? ? ? ?
-2, -1, -1, 150, 160, 170, 180, 190 // Array after sorting
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1054 次 |
最近记录: |