只对正值进行排序,并使用它的索引保持负值,因为它是一个数组

时间:2021-02-18 15:59:41

I need to sort the array in ascending order only for the positive value. For the negative value the index position will remain the same as it is.

我需要按升序对数组进行排序,仅用于正值。对于负值,指数位置将保持不变。

If the array is : int[] inputArray = {-1, 150, 190, 170, -1, -1, 160, 180}.

如果数组是:int [] inputArray = {-1,150,190,170,-1,-1,160,180}。

The output should be like this - int[] outputArray = {-1, 150, 160, 170, -1, -1, 180, 190}.

输出应该是这样的 - int [] outputArray = {-1,150,160,170,-1,-1,180,190}。

But in my case the output is this - int[] outputArray = {-1, 150, 170, 190, -1, -1, 160, 180}.

但在我的情况下输出是这样的 - int [] outputArray = {-1,150,170,190,-1,-1,160,180}。

Here is my code below :

这是我的代码如下:

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;
}

6 个解决方案

#1


7  

In the second loop, for every inputArray[j] you need to find next element which is greater than 0 before comparing.

在第二个循环中,对于每个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;
    }

#2


7  

Try to:

尝试:

  1. Extract only the positive values
  2. 仅提取正值
  3. Sort them using Collections.sort (or Array.sort)
  4. 使用Collections.sort(或Array.sort)对它们进行排序
  5. Go through the original array and replace the positive values by the ordered ones
  6. 浏览原始数组并用有序值替换正值

#3


5  

You could try to sort yourself, or extract just the positive values and sort them, but here is an alternate version that leaves input array unmodified (since returning new array from method would otherwise be unnecessary).

您可以尝试对自己进行排序,或者只提取正值并对它们进行排序,但是这里是一个替代版本,它保持输入数组不被修改(因为从方法返回新数组是不必要的)。

Code simply copies and sorts the input array first, then merges negative values from input array with positive values from sorted array. Since negative values were sorted first, there's no chance of overwriting sorted values being copies.

代码只是首先复制和排序输入数组,然后将输入数组中的负值与排序数组中的正值合并。由于负值首先排序,因此不可能覆盖排序值作为副本。

Code also doesn't box the values, as would otherwise be necessary for building a List<Integer> of positive values.

代码也不会封装值,否则将构建正值的List

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;
}

Test

测试

int[] inputArray = {-1, 150, 190, 170, -2, -1, 160, 180};
int[] outputArray = sortByHeight(inputArray);
System.out.println(Arrays.toString(outputArray));

Output

产量

[-1, 150, 160, 170, -2, -1, 180, 190]

The re-use of arr as both the sorted array of all values, and the result array, works because positive value will only be copied down, or stay where they are.

重复使用arr作为所有值的排序数组和结果数组,因为正值只能被复制下来,或者保持原样。

To illustrate:

为了显示:

-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

#4


3  

List<Integer> positives = new ArrayList<Integer>();
for (int i : inputArray) 
  if (i > 0) positives.add(i);
Collections.sort(positives);

int x = 0;
for (int y = 0; y < inputArray.length; y++)
  if (inputArray[y] > 0) inputArray[y] = positives.get(x++);

This extracts all the positive values from the input int array, sorts them, and replaces the positive values one by one.

这将从输入int数组中提取所有正值,对它们进行排序,并逐个替换正值。

#5


3  

Turning what @jean-logeart said into code:

转向@ jean-logeart所说的代码:

public static int[] sortByHeight(int[] inputArray) {
    // Extract only the positive values
    ArrayList<Integer> positiveValues = new ArrayList<>();
    for (int value: inputArray) {
        if (value > 0) positiveValues.add(value);
    }

    // Sort them using Collections.sort (or Array.sort)
    Collections.sort(positiveValues);

    // Go through the original array and replace the positive values by the ordered ones
    int positiveIndex = 0;
    for (int index = 0; index < inputArray.length; index++) {
        if (inputArray[index] > 0) {
            inputArray[index] = positiveValues.get(positiveIndex);
            positiveIndex++;
        }
    }

    return inputArray;
}

Running with the main() supplied in the question produces:

使用问题中提供的main()运行会产生:

-1, 150, 160, 170, -1, -1, 180, 190, 

#6


2  

How about a replacement in place like this:

这样的替换怎么样:

 int[] inputArray = { -1, 150, 190, 170, -1, -1, 160, 180 };

    Iterator<Integer> sorted = Arrays.stream(inputArray)
            .filter(x -> x > 0)
            .sorted()
            .boxed()
            .collect(Collectors.toList())
            .iterator();

    IntStream.range(0, inputArray.length)
            .forEach(x -> {
                if (inputArray[x] > 0) {
                    inputArray[x] = sorted.next();
                }
            });

#1


7  

In the second loop, for every inputArray[j] you need to find next element which is greater than 0 before comparing.

在第二个循环中,对于每个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;
    }

#2


7  

Try to:

尝试:

  1. Extract only the positive values
  2. 仅提取正值
  3. Sort them using Collections.sort (or Array.sort)
  4. 使用Collections.sort(或Array.sort)对它们进行排序
  5. Go through the original array and replace the positive values by the ordered ones
  6. 浏览原始数组并用有序值替换正值

#3


5  

You could try to sort yourself, or extract just the positive values and sort them, but here is an alternate version that leaves input array unmodified (since returning new array from method would otherwise be unnecessary).

您可以尝试对自己进行排序,或者只提取正值并对它们进行排序,但是这里是一个替代版本,它保持输入数组不被修改(因为从方法返回新数组是不必要的)。

Code simply copies and sorts the input array first, then merges negative values from input array with positive values from sorted array. Since negative values were sorted first, there's no chance of overwriting sorted values being copies.

代码只是首先复制和排序输入数组,然后将输入数组中的负值与排序数组中的正值合并。由于负值首先排序,因此不可能覆盖排序值作为副本。

Code also doesn't box the values, as would otherwise be necessary for building a List<Integer> of positive values.

代码也不会封装值,否则将构建正值的List

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;
}

Test

测试

int[] inputArray = {-1, 150, 190, 170, -2, -1, 160, 180};
int[] outputArray = sortByHeight(inputArray);
System.out.println(Arrays.toString(outputArray));

Output

产量

[-1, 150, 160, 170, -2, -1, 180, 190]

The re-use of arr as both the sorted array of all values, and the result array, works because positive value will only be copied down, or stay where they are.

重复使用arr作为所有值的排序数组和结果数组,因为正值只能被复制下来,或者保持原样。

To illustrate:

为了显示:

-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

#4


3  

List<Integer> positives = new ArrayList<Integer>();
for (int i : inputArray) 
  if (i > 0) positives.add(i);
Collections.sort(positives);

int x = 0;
for (int y = 0; y < inputArray.length; y++)
  if (inputArray[y] > 0) inputArray[y] = positives.get(x++);

This extracts all the positive values from the input int array, sorts them, and replaces the positive values one by one.

这将从输入int数组中提取所有正值,对它们进行排序,并逐个替换正值。

#5


3  

Turning what @jean-logeart said into code:

转向@ jean-logeart所说的代码:

public static int[] sortByHeight(int[] inputArray) {
    // Extract only the positive values
    ArrayList<Integer> positiveValues = new ArrayList<>();
    for (int value: inputArray) {
        if (value > 0) positiveValues.add(value);
    }

    // Sort them using Collections.sort (or Array.sort)
    Collections.sort(positiveValues);

    // Go through the original array and replace the positive values by the ordered ones
    int positiveIndex = 0;
    for (int index = 0; index < inputArray.length; index++) {
        if (inputArray[index] > 0) {
            inputArray[index] = positiveValues.get(positiveIndex);
            positiveIndex++;
        }
    }

    return inputArray;
}

Running with the main() supplied in the question produces:

使用问题中提供的main()运行会产生:

-1, 150, 160, 170, -1, -1, 180, 190, 

#6


2  

How about a replacement in place like this:

这样的替换怎么样:

 int[] inputArray = { -1, 150, 190, 170, -1, -1, 160, 180 };

    Iterator<Integer> sorted = Arrays.stream(inputArray)
            .filter(x -> x > 0)
            .sorted()
            .boxed()
            .collect(Collectors.toList())
            .iterator();

    IntStream.range(0, inputArray.length)
            .forEach(x -> {
                if (inputArray[x] > 0) {
                    inputArray[x] = sorted.next();
                }
            });