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;
}
Using brute force approach to sort only positive numbers in the array. We will first filter out the positive numbers from the given array and sort them in required order. After that we will use a temp array to store the sorted array and extra variable to track the elements of the filtered and sorted positive array.
In order to sort numbers, you'll need to write a function that returns a negative number if a is less than b , returns a positive number if b is less than a , and returns 0 if the numbers are the same. This can easily be accomplished by subtracting the numbers.
No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.
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;
}
Try to:
Collections.sort
(or Array.sort
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With