I'm writing a code which suppresses or pushes the negative elements of an int array to the bottom of the array, without altering the sequence of the rest of the array. Which basically means it is not the mere sorting of the array. So far I've got this:
class supparray
{
public static void main(String args[])
{
int array1Index = 0, array2Index = 0;
int array[] = {1, -8, 5, 12, -6, 2, 4};
int length = array.length;
int array1[] = new int[length] ;
int array2[] = new int[length];
for(int i = 0; i<array.length; i++)
{
if(array[i]<0)
{
array1[i] = array[i];
array1Index+=1;
}
else
{
array2[i] = array[i];
array2Index+=1;
}
for(int j = 0; j<array2Index; j++)
{
array1[array1Index+j] = array2[j];
}
}
System.out.println(array1);
}
}
So, the code compiles, but I'm getting a very weird output. Like, it doesn't even have only numbers. My output is: [I@104c575 I really have no idea as to what's wrong. Is it my logic, or is my JDK really messed up? TIA.
There are two answers here. First is the answer to your code. You must properly format an array.
The second answer is just another approach to your problem. It's a bit cleaner and more efficient, and at least checks to make sure your array is longer than 1 before beginning to manipulate.