compact array
OSucceeds: arrays
Summary
Compact array
- implements list
| Operation | Method | Performance |
|---|---|---|
get(i) | direct access | - |
search(v) | linear search | - - |
insert(i, v) | shift elements [i,n−1] right, place v at i | - - 0, shift the other elements |
remove(i) | shift elements [i+1,n−1] left | - - |
Strengths
- direct indexing
, elements are contiguous - good if the maximum
is known
Limitations
- fixed size issue (if
too small → overflow, too large → wasted space) - inefficient when the maximum
is unknown and ifinsertandremoveare used often
Concept
Data structure
- contiguous storage with no gaps
- operations must maintain compactness(no empty slots in between)
Variable-sized arrays
- overcomes issues with fixed-sized arrays
- once full, allocate a new array(2× larger), copy elements
- eg.
std::vector(C++),list(Python),ArrayList(Java)
the copying of elements into the new array is an amortized
operation, it happens so infrequently(ideally) that we can consider it as
Application
Finding min and max
java
List<Integer> A = new ArrayList<>();
...
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int x : A) { // n times
if (x < min) min = x;
if (x > max) max = x;
}
System.out.println("Min = " + min + ", Max = " + max);
Naive duplicate detection
java
List<Integer> A = new ArrayList<>();
...
boolean hasDuplicate = false;
for (int i = 0; i < A.size(); i++) { // n times
for (int j = i + 1; j < A.size(); j++) { // n times
if (A.get(i).equals(A.get(j))) {
hasDuplicate = true;
System.out.println("Duplicate found: " + A.get(i));
}
}
}
if (!hasDuplicate) {
System.out.println("No duplicates found.");
}