sort only the positive value and remain the negative value with it's index as it is of an array

Sumon Bappi :

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

The output should be like this - 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}.

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

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

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442254&siteId=1