I am a fairly new programmer, and want to create a method that will start with an empty array, and allow me to call on it, in order to add values to that array in ascending order.
For example:
insertInOrder(5);
insertInOrder(3);
insertInOrder(7);
insertInOrder(9);
insertInOrder(12);
should return an array with values:
0: 3
1: 5
2: 7
3: 9
4: 12
Any tips on how I can go about this without using java prebuilt methods like "Array.sort" would be much appreciated. Thank you!
Below is my attempt at this code; however, all I could implement was adding a value to the end of the array if it is the largest number.
For example:
insertInOrder(1);
insertInOrder(4);
insertInOrder(9);
insertInOrder(17);
insertInOrder(26);
would work, but this code would not:
insertInOrder(2);
insertInOrder(4);
insertInOrder(1);
insertInOrder(3);
insertInOrder(19);
Code:
public class InOrder
{
int[] arry = new int[20];
int target = -1;
int elements = 0;
public static void main(String[] args)
{
InOrder i = new InOrder();
i.insertInOrder(6);
i.insertInOrder(7);
i.insertInOrder(12);
i.insertInOrder(17);
i.insertInOrder(19);
i.insertInOrder(28);
for(int k = 0; k < 20; k++)
{
System.out.println(i.arry[k]);
}
}
public void insertInOrder(int n)
{
if (elements == 0)
{
arry[0] = n;
elements++;
}
else
{
for (int i = 0; i < elements; i++)
{
if (n > arry[i])
{
target = i;
}
}
if (target == -1)
{
target = 0;
}
if (n > arry[target])
{
for (int x = target; x < elements; x++)
{
if(x + 1 == elements)
{
arry[x + 1] = n;
elements++;
break;
}
}
}
}
}