Question:
Java array insert/delete help!?
Cuong P
2009-09-05 10:08:32 UTC
I have 2 files and confused on how to insert #'s in the proper location in an array by shifting contents as needed. Maintain ascending sequence as numbers are inserted (I can't just numbers at the end of the list and then resort it)
I'm not suppose to use any API.
Three answers:
Mark aka jack573
2009-09-08 14:43:10 UTC
You would need to make a method that either calls itself (recursion) or a method with a while or for loop.



If you have not learnt recursion, then use the while or for loop.



A basic example would be:



void sortArray(int[] array)

{

int element;

int lowest;

int lowestIndex;

for (int i = 0; i < array.length; i++)

{

// This will make the loop go around the array once. You may not need it to do the last iteration, so you could have

// if (int i = 0; i < array.length - 1; i++)

// Then another loop that checks for the lowest number in the array.

// Each time it comes to this loop, it does not check the numbers you have already moved.

for (int j = i; j < array.length; j++)

{

lowest = array[i];

// Again, you may want to use

// for (int j = i; j < array.length - 1; j++)

element = array[j];

if (element < lowest) {

lowest = element;

lowestIndex = j;

}

} // end the j for loop

element = array[i];

array[i] = lowest;

array[lowestIndex] = element;

// The above three lines swap the positions of the lowest number.

} // end the i for loop

}



I have not tested the code, but that is the way you would sort it. You may need to change it slightly, if it does not work.



but since you are asking a different question, like how to add a number in correct order, you could do something like this.



int[] insert(int[] array, int numToInsert)

{

// Now I don't know if you have to resize the array, but do it here if needed.

int newArray[array.length + 1];

int element;

// then using a similar technique to the above.

for (int i = 0; i < array.length; i++)

{

element = array[i];

if (element < numToInsert)

{

newArray[i] = array[i];

}

else

{

// Now put the new num in here and move all other nums to one space on.

newArray[i] = numToInsert;

for (int j = i + 1; j < array.length; j++, i++) // This increments both i and j.

{

newArray[j] = array[i];

} // end j for

} // end if else

} // end i for

return newArray;

}



Hope that helps you.
Jessica
2016-04-10 07:23:31 UTC
Probably the top contributors way is good one , but if you want to know the logic , 1. assign the first element as max 2. loop through the elements and compare the array elements with the max value 3. if found greater than the current max element update it . 4. print the max value , that is the maximum value in the array
?
2009-09-07 04:05:48 UTC
//pk



Java itself has Collection framework to solve your problem.



http://java.sun.com/docs/books/tutorial/collections/index.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...