Chapter 3: Arrays

Chapter 3: Arrays · Study Questions
The array conceptArrays in JavaStack and heapArray algorithmsMultidimensional arraysComplexitySorting
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Basic Concepts

Question 1: Properties of Arrays

Which statement about Java arrays is true?

C is correct: contiguous memory makes both address computation and caching easy. B is tempting but wrong: access is O(1), yet inserting in the middle means shifting the later elements → O(n). The size is fixed (A), and sorting and searching are done with java.util.Arrays (D).

Short Answer · Basic Concepts

Question 2: Array Covariance

Does this code compile? What happens when it runs, and why?

String[] names = {"Ann", "Alice"};
Object[] objects = names;
objects[0] = 42;
System.out.println(objects.length);
Show answer

It compiles. Arrays are covariant: since String is a subtype of Object, String[] counts as a subtype of Object[], and 42, boxed as an Integer, can be assigned to an Object.

At run time, line 3 throws ArrayStoreException: java.lang.Integer and println is never reached. The object really is a String[], and the JVM checks the type on every store.

The price: the type error is caught at run time instead of compile time. Generics are not covariant: List<Object> l = new ArrayList<String>(); doesn't even compile.

Short Answer · Basic Concepts

Question 3: Computing an Address

Why is access by index O(1)? An int array starts at address 1000. What is the address of a[5]? Show your work.

Show answer
  • The elements are contiguous and all the same size, so one calculation gives the address: address = start + i × element size. The time doesn't depend on the array's length → O(1).
  • A Java int takes 4 bytes: a[5] = 1000 + 5 × 4 = 1020.

Multiple Choice · Arrays in Java

Question 4: Default Values

What does this code print?

double[] d = new double[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
System.out.println(d[0] + " " + b[1]
                   + " " + s[0]);

Every element of an array created with new gets its type's default value: double → 0.0, boolean → false, object (String) → null (and char → '\u0000'). Unlike local variables, array elements are never uninitialized, so C is wrong; the default for String is null, not "".

Short Answer · Arrays in Java

Question 5: Declaration Errors

Which of the numbered lines fail to compile? Fix each one.

int[] a = {1, 2, 3};          // 1
int[] b;  b = {4, 5};         // 2
int[] c = new int[] {6, 7};   // 3
int[] d = new int[2] {8, 9};  // 4
int n = a.length();           // 5
Show answer

The faulty lines are 2, 4, and 5.

  • 2: A bare initializer list is allowed only in a declaration. Fix: b = new int[] {4, 5};
  • 4: You can't give both a size and a list; the number of elements sets the size. Fix: new int[] {8, 9}
  • 5: On an array, length is a field, not a method: a.length (on a String it is s.length()).

Lines 1 and 3 are fine (the form in line 3 also works in a later assignment).

Multiple Choice · Arrays in Java

Question 6: Reference or Copy?

What does this code print?

int[] arr = {1, 2, 3};
int[] r = arr;
int[] k = Arrays.copyOf(arr, arr.length);
r[0] = 99;
k[1] = 50;
System.out.println(arr[0] + " " + arr[1]);

r = arr copies only the address: r and arr point to the same object on the heap, so r[0] = 99 changes the array. Arrays.copyOf creates a new object and copies the elements one by one (O(n)); a change to k doesn't show up in arr, so C is wrong.

Short Answer · Arrays in Java

Question 7: java.util.Arrays

What does the program print? Briefly justify each line.

int[] a = {5, 3, 8};
int[] b = {5, 3, 8};
System.out.println(a == b);
System.out.println(Arrays.equals(a, b));
int[] c = Arrays.copyOf(a, 5);
Arrays.sort(a);
System.out.println(Arrays.toString(a)
        + " " + Arrays.toString(c));
Show answer
false
true
[3, 5, 8] [5, 3, 8, 0, 0]
  • == compares references: a and b are different objects → false.
  • Arrays.equals compares the lengths and then the elements one by one → true (O(n)).
  • copyOf(a, 5) creates a new array whose extra cells get the default 0. The copy was taken before sorting, so c is unsorted.
  • sort sorts in place (O(n log n)); println(a) would have printed [I@….

Multiple Choice · Arrays in Java

Question 8: Off-by-One

What happens when this code runs?

int[] a = new int[5];
for (int i = 0; i <= a.length; i++)
    a[i] = i;

The valid indices are 0…length − 1 = 0…4; with <=, the last iteration accesses a[5] (off by one). Java checks every access at run time and throws an exception, which ends the program if uncaught. D is how C behaves, since it doesn't check. The fix is i < a.length.

Multiple Choice · Array Algorithms

Question 9: The Mean of an Empty Array

If the user enters 0 as the size in readArray, what is printed?

double[] arr = readArray(sc);  // size 0
double sum = 0;
for (int i = 0; i < arr.length; i++)
    sum += arr[i];
System.out.println("Average: "
        + sum / arr.length);

new double[0] is a legal, empty array, so the loop never runs. 0.0 / 0 is floating-point division and gives NaN. B would be right if both the sum and the divisor were int. Better to warn the user.

Code Trace · Array Algorithms

Question 10: Tracing the Mode

What does mode({5, 2, 5, 2, 9}) return? If two values occur equally often, which one wins?

The copy is sorted, bringing equal values together. The caller's array is left alone.

The first value (2) holds the record for now: once.

s[1] = 2 == s[0] → the run continues, count = 2.

2 > 1 → new record: best = 2, 2 times.

s[2] = 5 ≠ 2 → new value, so the count resets to 1. 1 > 2 is false.

s[3] = 5 == s[2] → count = 2.

2 > 2 is false: because the comparison is >, a tie doesn't change the record.

s[4] = 9 ≠ 5 → count 1. The loop ends.

return 2. Both 2 and 5 occur twice; the one seen first (the smallest), 2, stays. O(n log n) + O(n).

static int mode(int[] arr) {
  int[] s = arr.clone();
  Arrays.sort(s);
  int best = s[0], bestCount = 1;
  int count = 1;
  for (int i = 1; i < s.length; i++) {
    if (s[i] == s[i - 1]) count++;
    else count = 1;
    if (count > bestCount) {
      bestCount = count; best = s[i];
    }
  }
  return best;
}

Multiple Choice · Array Algorithms

Question 11: Mode Without Sorting

If the Arrays.sort line is removed from the mode method, what does the code below print?

int[] s = {1, 4, 2, 4, 3, 4}; // unsorted
int best = s[0], bestCount = 1, count = 1;
for (int i = 1; i < s.length; i++) {
  if (s[i] == s[i - 1]) count++;
  else count = 1;
  if (count > bestCount) {
    bestCount = count; best = s[i];
  }
}
System.out.println(best);

The algorithm only counts equal neighbors. In this unsorted array no two neighbors are equal, so count stays 1, the record never changes, and the first element, 1, is returned. The real mode is 4 (A), but the 4s aren't adjacent, so it is never found. That is why the array must be sorted first.

Short Answer · Array Algorithms

Question 12: Caesar Cipher

What does encrypt("YAZ", 4) return, and with which k should the same method be called to decrypt the result?

static String encrypt(String message, int k) {
    char[] chars = message.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        int pos = chars[i] - 'A';
        chars[i] = (char) ('A' + (pos + k) % 26);
    }
    return new String(chars);
}
Show answer
letterpos(pos + 4) % 26result
Y2428 % 26 = 2C
A04E
Z2529 % 26 = 3D

Result: "CED". % 26 wraps a position past the end back to the start.

To decrypt, use k = 26 − 4 = 22: encrypt("CED", 22) → "YAZ".

Strings are immutable, so the letters are copied into a char[] with toCharArray() and changed in place. char values are integers. Each letter is handled once: O(n).

Short Answer · Array Algorithms

Question 13: Reversing in Place

The method below reverses an array in place, without a second array. Fill in the blanks.

void reverse(int[] arr) {
    int left = 0;
    int right = ________;
    while (________) {
        int temp = arr[left];
        ________
        ________
        ________
        ________
    }
}
Show answer
int right = arr.length - 1;
while (left < right) {
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;
    left++;
    right--;
}

Swap the outermost pair and move both indices toward the middle, continuing while left < right (n/2 swaps).

Short Answer · Multidimensional Arrays

Question 14: A null Row in a Jagged Array

What does the code print, and what happens on the last line?

int[][] m = new int[3][];
m[1] = new int[4];
m[1][2] = 5;
System.out.println(m.length + " "
        + m[1].length + " " + m[0]);
System.out.println(m[0][0]);
Show answer

The first line prints 3 4 null; the last line throws a NullPointerException.

  • In Java a matrix is an array of arrays. new int[3][] creates only the outer array of 3 references; the rows don't exist yet (null).
  • m.length is the number of rows (3); m[1].length is that row's own length (4). Rows can differ in length: a jagged array.
  • m[0] is null, so accessing m[0][0] throws. The fix: first write m[0] = new int[k];

Short Answer · Multidimensional Arrays

Question 15: Shallow and Deep Copy

What does the program print? Explain each value in terms of shallow and deep copies.

int[][] m = { {1, 2}, {3, 4} };
int[][] s = m.clone();
int[][] d = { m[0].clone(), m[1].clone() };
s[1][0] = 8;
d[0][0] = 6;
s[0] = new int[] {0, 0};
System.out.println(m[0][0] + " " + m[1][0]
        + " " + s[0][0] + " " + d[1][0]);
Show answer

Output: 1 8 0 3

  • m.clone() copies only the outer array: s holds the same row references as m (a shallow copy). s[1][0] = 8 changes the shared row → m[1][0] = 8.
  • s[0] = new int[]… changes only a reference in s's own outer array; m[0] is unaffected → m[0][0] = 1, s[0][0] = 0.
  • Each row of d was cloned separately (a deep copy). When d[1] was cloned, m[1][0] was still 3 → d[1][0] = 3. Changes to d don't affect m.

Multiple Choice · Multidimensional Arrays

Question 16: A Three-Dimensional Array

When the loops finish, what is u[2][1][0], and how many times has the innermost assignment run?

int[][][] u = new int[3][3][3];
for (int x = 0; x < 3; x++)
  for (int y = 0; y < 3; y++)
    for (int z = 0; z < 3; z++)
      u[x][y][z] = x * 9 + y * 3 + z + 1;

2·9 + 1·3 + 0 + 1 = 22. Each dimension adds a nested loop: 3 × 3 × 3 = 27 assignments. B forgets the "+1", C counts only two loops, and D mixes up the weights (x·3 + y·9).

Short Answer · Complexity

Question 17: Inserting in the Middle

With a = {3, 8, 2, 6, 0, 0} and size = 4, what are the array and the return value after insert(a, 4, 1, 5)? Why does the shifting start from the right?

static int insert(int[] a, int size,
                int index, int value) {
  // precondition: size < a.length
  for (int k = size; k > index; k--)
    a[k] = a[k - 1];   // shift right
  a[index] = value;
  return size + 1;
}
Show answer
stepa
k = 4: a[4] = a[3]{3, 8, 2, 6, 6, 0}
k = 3: a[3] = a[2]{3, 8, 2, 2, 6, 0}
k = 2: a[2] = a[1]{3, 8, 8, 2, 6, 0}
a[1] = 5{3, 5, 8, 2, 6, 0}

Result {3, 5, 8, 2, 6, 0}, return value 5; 3 shifts.

Starting from the left, a[2] = a[1] would overwrite 2, and then 8 would be copied all the way to the right: data is lost. Inserting at the front takes n shifts → O(n); inserting at the end, when there is room, O(1).

Multiple Choice · Complexity

Question 18: Sorting Sorted Input

You are given an n-element array that is already in ascending order. Which algorithm finishes in O(n) time on this input?

In insertion sort each key is compared once with its left neighbor and nothing shifts: n − 1 comparisons → O(n). Selection sort always makes n(n−1)/2 comparisons (O(n²)); merge sort always takes O(n log n) and needs O(n) extra space. D is the strongest distractor: sorted input with the first element as pivot is quick sort's worst case, O(n²). (Arrays.sort uses dual-pivot quick sort for primitive arrays and stable TimSort for object arrays.)

Short Answer · Complexity

Question 19: Selection Sort

Selection sort runs on {29, 10, 14, 37, 13}. Each pass finds the smallest element of the unsorted part and swaps it with the first element of that part. What does the array look like after each pass, and how many comparisons are made in total?

Show answer
passswaparray
129 ↔ 10{10, 29, 14, 37, 13}
229 ↔ 13{10, 13, 14, 37, 29}
314 stays{10, 13, 14, 37, 29}
437 ↔ 29{10, 13, 14, 29, 37}

Comparisons: 4 + 3 + 2 + 1 = 10 = n(n − 1)/2. This count doesn't depend on the input: best, average, and worst case are all O(n²), with O(1) extra space. The last element falls into place by itself, so n − 1 passes suffice.

Code Trace · Complexity

Question 20: Tracing Insertion Sort

How many shifts (a[j] = a[j - 1]) does insertionSort({6, 3, 8, 2}) make in total?

The sorted part is {6}. The key 3 is set aside.

6 > 3 → 6 shifts one place right; j = 0.

j == 0: we've reached the front, so a[0] = 3. The first 2 elements are sorted.

The key is 8.

6 > 8 is false → the while loop never runs; 8 stays put.

The key 2 is smaller than the whole sorted part.

8 > 2 → shift right.

6 > 2 → shift right.

3 > 2 → shift right; j = 0.

a[0] = 2 → sorted. 4 shifts = the number of inversions: (6,3), (6,2), (3,2), (8,2). Worst case O(n²); O(n) on a sorted array.

static void insertionSort(int[] a) {
  for (int k = 1; k < a.length; k++) {
    int key = a[k];
    int j = k;
    while (j > 0 && a[j - 1] > key) {
      a[j] = a[j - 1];   // shift right
      j--;
    }
    a[j] = key;      // insert
  }
}

Multiple Choice · Summary

Question 21: Common Mistakes

Let a and b be int[] variables. Which code correctly does what it claims?

clone() creates a new array, so changes to b don't reach a (A). B compares references; comparing contents takes Arrays.equals. C prints type@address, like [I@…; use Arrays.toString. The bug in D is easy to miss: binary search needs a sorted array; searching {8, 3, 5, 1} for 8, for example, returns −5 (not found).

Code Trace · Complexity

Question 22: Tracing a Deletion

With a = {6, 1, 8, 3, 7, 0} and size = 5, what are the array and the return value after remove(a, 5, 2)? How many shifts are made?

The valid elements are a[0..4]; a[5] is unused. We delete a[2] = 8.

k = 2: a[2] = a[3] → 3 overwrites 8, which is now gone.

k = 3: a[3] = a[4] → 7 shifts one place left.

4 < size − 1 = 4 is false → the loop ends after 2 shifts.

a[4] = 0: clear the leftover 7 in the old last cell.

The new size is 4: {6, 1, 3, 7}. Shifts = size − index − 1 = 2. Deleting at the front would take 4 shifts → O(n); deleting at the end, O(1).

static int remove(int[] a, int size, int index) {
  for (int k = index; k < size - 1; k++)
    a[k] = a[k + 1];   // shift left
  a[size - 1] = 0;    // clear the old last cell
  return size - 1;    // new size
}

Multiple Choice · Array Algorithms

Question 23: Reversing with a Wrong Loop Condition

The loop condition in reverse has been changed as shown. What is {1, 2, 3, 4, 5} after the call?

int start = 0;
int end = arr.length - 1;
while (start < arr.length) { // changed
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
}

The loop runs 5 times: (0, 4) and (1, 3) turn the array into {5, 4, 3, 2, 1}; (2, 2) swaps an element with itself; (3, 1) and (4, 0) swap the same pairs back, undoing the work. When start reaches 5 (end = −1) the loop ends, so a[−1] is never touched (B). A is what the correct condition (n/2 swaps) gives. D pictures only arr[start] = arr[end], without temp.

Multiple Choice · Multidimensional Arrays

Question 24: The Shape of a Transpose

The code below uses the transpose method from the slides (t[j][i] = m[i][j]). What are t.length and t[1][2]?

int[][] m = {{1, 2}, {3, 4}, {5, 6}};
int[][] t = transpose(m);

m is 3×2, so t = new int[2][3] has 2 rows and 3 columns: t = {{1, 3, 5}, {2, 4, 6}}. t[1][2] = m[2][1] = 6. C thinks in m's dimensions (m[1][2] really is out of bounds). B confuses it with t[0][2] = 5; A assumes the number of rows stays the same.

Short Answer · Array Algorithms

Question 25: Computing the Median

For the median(double[]) method from the slides:

  1. What do median({7, 1, 9, 4, 6, 2}) and median({7, 1, 9, 4, 6}) return? Show the indices m1 and m2.
  2. If the method took an int[] and returned an int (keeping (s[m1] + s[m2]) / 2), what would it return for {3, 8, 1, 4}?
  3. Why does the method call clone() first? What is its time cost?
Show answer

1. s = {1, 2, 4, 6, 7, 9}, m1 = 2, m2 = 3 → (4 + 6) / 2 = 5.0. Odd size: s = {1, 4, 6, 7, 9}, s[5 / 2] = s[2] = 6.0.

2. s = {1, 3, 4, 8} → 7 / 2 = 3: integer division drops the fraction. The right answer is 3.5 (with / 2.0 and a double return type).

3. Arrays.sort sorts in place; without the copy, the caller's array would change. Time O(n log n), extra space O(n).

The End

Chapter 3: Arrays: Study Questions
Lecture slides: Chapter 3: Arrays
1 / 1 Sercan KÜLCÜ. All rights reserved.