int pos = 0; boolean found = false; while (pos < values.size() && !found) { if (values.get(pos) > 100) { found = true; } else { pos++; } } if (found) { System.out.println("Position: " + pos); } else { System.out.println("Not found"); }
The algorithm above locates the first match. What if you want to get all matching values?
ArrayList<Double>
int[]
arrayint findFirst(double[] values, double limit, int startPosition)
and call it repeatedly
values[pos] = values[valuesSize - 1]; valuesSize--;
for (int i = pos; i < valuesSize - 1; i++) { values[i] = values[i + 1]; } valuesSize--;
if (valuesSize < values.length) { values[valuesSize] = newElement; valuesSize++; }
if (valuesSize < values.length) { for (int i = valuesSize; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; valuesSize++; }
Consider this variation of the insertion algorithm.
if (valuesSize < values.length) { for (int i = pos + 1; i < valuesSize; i++) { values[i] = values[i - 1]; } values[pos] = newElement; valuesSize++; }
What is the contents of values
after the loop when
pos
is 3, newElement
is 10
,
valuesSize
is 6, and before the loop, values
is
1 4 9 16 25 36 0 0 0 0
double[] values = new double[6];
. . . // Fill array
double[] prices = values;
double[] prices = Arrays.copyOf(values, values.length);
values = Arrays.copyOf(values, 2 * values.length);
int valuesSize = 0;
while (in.hasNextDouble())
{
if (valuesSize == values.length)
values = Arrays.copyOf(values, 2 * values.length);
values[valuesSize] = in.nextDouble();
valuesSize++;
}
Ann | Bob | Cindy
for (int i = 0; i < names.size(); i++) { if (i > 0) { System.out.print(" | "); } System.out.print(names.get(i)); }
The following replacement has been suggested for the algorithm that prints element separators:
System.out.print(names.get(0)); for (int i = 1; i < names.size(); i++) System.out.print(" | " + names.get(i));
What is problematic about this suggestion?
final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS];
board[1][1] = "x"; board[2][1] = "o";
for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";
for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) board[i][j] = " ";