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

Viewed 3380

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;
}
7 Answers
public static void sortByHeight(int[] inputArray) {
    List list = new ArrayList();
    for (int i = 0; i < inputArray.length; i++) {
        if (inputArray[i] > 0)
            list.add(inputArray[i]);
    }
    Collections.sort(list);
    int j=0;
    for (int i = 0; i < inputArray.length; i++) {
        if (inputArray[i] > 0){
            inputArray[i] = Integer.parseInt(list.get(j).toString());
        j++;}
    }

    for (int i = 0; i < inputArray.length; i++) {
        System.out.println(inputArray[i]);
    }
}
Related