Arrays: Data Structures
Arrays: Data Structures
Data Structures
Ching-Fang Hsu
Dept. of Computer Science and Information Engineering
National Cheng-Kung University
What is “Array”?
2
public class ArrayExample1 {
public static void main(String[] argv) {
int[] x;
x = new int[20];
for (int i = 0; i < x.length; i++) {
x[i] = 20 - i;
}
final variable
}
}
public class ArrayExample2 {
public static void main(String[] args) { homogeneous
int[] a1 = { 1, 2, 3, 4, 5 };
Object[] a2 = new Object[] {
new Integer(47), new Long(10), new Float(3.14),
new Double(11.11);
}
3
}
heterogeneous
Array vs. ArrayList in Java
Explicitly specified size
5
Use Case 1: Ordered Lists
6
Use Case 1: Ordered Lists
(contd.)
Sequential mapping works well for most
operations on ordered lists in constant time,
except insertion and deletion.
Data movement
7
Example --- Polynomials
ADT
8
Two non-zero polynomials
public Polynomial Add(Polynomial p1, Polynomial p2) {
p1 = Remove(p1, LeadExp(p1));
Operation Add
p2 = Remove(p2, LeadExp(p2));
break;
Comparing terms from the two polynomials until one or
case 1:
d = Attach(d, Coef(p1, LeadExp(p1)), LeadExp(p1).intValue());
bothp1of= the polynomials
Remove(p1, becomes empty
LeadExp(p1));
break;
} Append the
}
polynomial with
for(; IsZero(p1); p1 = Remove(p1, LeadExp(p1))) { remaining terms
d = Attach(d, Coef(p1, LeadExp(p1)), LeadExp(p1));
}
for(; IsZero(p2); p2 = Remove(p2, LeadExp(p2))) {
d = Attach(d, Coef(p2, LeadExp(p2)), LeadExp(p2));
}
return d;
}
9
package array;
11
Example: Polynomials ---
package array;
int expon;
float coef;
Option 2 public Struct2() {
Representing ai xi as
} a structure
(Optional) Using only onevoid
public global array of this
setExpon(int e) { structure to
store all terms of a polynomial
expon = e;
}
Struct2
public void setCoef(float c) {
coef = c;
}
12
The Polynomial Abstract Data
Type – Representation (contd.)
A(x) = 2x1000 + 1 B(x) = x4 + 10x3 + 3x2 + 1
coef 2 1 1 10 3 1
expon 1000 0 4 3 2 0
0 1 2 3 4 5 6
2x1000
13
The Polynomial Abstract Data
Type – Representation (Contd.)
No limit on the number of polynomial terms and
the maximum degree stored in a polynomial if
arraylists are used.
The main drawback: About twice as much
space as option 1 is needed when all the terms
are nonzero.
14