I have to make a program in Java to create a sorted array in descending order. When i try to insert 10, 3 it is ok, but when i insert 10, 3, 8 the result is 10, 8, 0. For some reason the 0 appears on the end. Also when i try to imput negative numbers like -2 the result becomes -2, 8, 0. Can someone help? Also, is bubble sort the correct method for this kind of insertion? (Sorry for my english it is my first time here). Thank you for your time.
private int searchPosition(int a)
{
int position = 0;
for (int i = 0; i < array.length(); i++)
{
if(array[i] != a)
{
if((array[i] > a) && (array[i + 1] < a))
{
position = i + 1;
}
}
else
{
position = i;
}
}
return position;
}
public boolean insert(int a)
{
int position;
boolean exists;
int temp;
if (size == capacity)
{
System.out.println("The array is full.");
return false;
}
else
{
exists = //here i call a method to make sure the element to insert doesn't exist in the array
if (exists == false)
{
//Bubble Sort in desceding order
for (int i = 0; i < array.length(); i++)
{
for (int j=0; j < array.length() - i; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
position = searchPosition(a);
//move elements one position to the right
for (int i = array.length(); i < position; i--)
{
array[i] = array[i - 1];
}
array[position] = a;
//place a in the free position
size++;
return true;
}
else
{
System.out.println("The element" + a + " already exists in the array.");
return false;
}
}
}