4. ArrayList and Binary Search

Java ArrayList

java.util.ArrayList

Methods

Characteristics

Dynamically Change Length


Amortized Analysis

Runtime Complexity Analysis of add(E e) Method

List<Integer> numbers = new ArrayList<Integer>(4);

Assuming doubling up the array

Running Time # of Elements Array Length
numbers.add(1) 1 1 4
numbers.add(2) 1 2 4
numbers.add(3) 1 3 4
numbers.add(4) 1 4 4
numbers.add(5) 5 5 8
numbers.add(6) 1 6 8
numbers.add(7) 1 7 8
numbers.add(8) 1 8 8
numbers.add(9) 9 9 16

Use banker’s (accounting) method to show Amortized Analysis

Running time # of elements Array length Allocated dollars Cost Saved dollars Balance
1 1 4 3 1 2 2
1 2 4 3 1 2 4
1 3 4 3 1 2 6
1 4 4 3 1 2 8
5 5 8 3 5 -2 6
1 6 8 3 1 2 10
1 7 8 3 1 2 12
1 8 8 3 1 2 12
9 9 16 3 9 -6 6

Conclude that add(E e) method has amortized constant time due to the allocated dollars per operation

Latency Issue of Amortized Constant Time


Prerequisite: The array is sorted.

public static int binarySearch(int[] data, int key) { int l = 0; int r = data.length - 1; int mid; while (true) { if (l > r) { return -1; } mid = l + (r - l) / 2; // Not mid = (l + r)/2 if (data[mid] == key) { return mid; } if (data[mid] < key) { l = mid + 1; } else { r = mid - 1; } } }

Time Complexity

Binary Search: $O(\log n)$

Integer Overflow

Avoid potential integer overflow issue with mid = l + (r - l) / 2

Array & ArrayList

  1. Random access
  2. No holes allowed -> Shifts
  3. Immutable length -> Memory/Latency issue

Back to Home Next Lecture