9.2.3.1. How many bytes int array?
Solution.
20 bytes
array initializer | array length |
binary search | data structure |
element | element type |
insertion sort | multidimensional array |
one-dimensional array | polymorphic sort method |
selection sort | sequential search |
sorting | subscript |
two-dimensional array |
0, 1,
… , N-1
.arrayname.length - 1
. The array’s length
instance variable can be used as a bound for loops that process the array.new
and causes the compiler to allocate memory for the array’s elements: int arr[]; // Declare a one-dimensional array variable
arr = new int[15];// Allocate 15 int locations for it
int twoDarr[][]; // Declare a two-dimensional array variable
twoDarr = new int[10][15]; // Allocate 150 int locations
length
variable.farr[farr.length - 2] == 4.4
double farr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
for (int k=0; k < farr.length; k++) {
System.out.print(farr[k] + " ");
}
public static void main(String[] argv) {
AnalyzeFreq af = new AnalyzeFreq();
af.countLetters("Now is the time for all good students" +
" to study computer related topics.");
af.printArray();
} //main()
24 18 90 1 0 85 34 18 // Initial 18 24 90 1 0 85 34 18 // Pass 1
24 18 90 1 0 85 34 18 // Initial 18 24 90 1 0 85 34 18 // Pass 1 18 24 90 1 0 85 34 18 // Pass 2 1 18 24 90 0 85 34 18 // Pass 3 0 1 18 24 90 85 34 18 // Pass 4 0 1 18 24 85 90 34 18 // Pass 5 0 1 18 24 34 85 90 18 // Pass 6 0 1 18 18 24 34 85 90 // Pass 7
24 18 90 1 0 85 34 18 // Initial 0 18 90 1 24 85 34 18 // Pass 1
24 18 90 1 0 85 34 18 // Initial 0 18 90 1 24 85 34 18 // Pass 1 0 1 90 18 24 85 34 18 // Pass 2 0 1 18 90 24 85 34 18 // Pass 3 0 1 18 18 24 85 34 90 // Pass 4 0 1 18 18 24 85 34 90 // Pass 5 0 1 18 18 24 34 85 90 // Pass 6 0 1 18 18 24 34 85 90 // Pass 7
double temp = 0; temp = var1; var1 = var2; var2 = temp;
myArr[3]
will persist after the method finishes.m
is changed within the method, that change will not affect k
, which is a value argument.smallest = k; for (int i k+1; i<arr.length; i++) { if (arr[i] < arr[smallest]) smallest = j; } swap(arr, k, smallest);
key iteration low high mid 21 0 0 13 6 21 1 7 13 10 21 2 7 9 8 21 3 9 9 9 21 4 10 9 failure
java.util.Arrays.sort()
Method
compareTo()
for LetterFreq
:public int compareTo(Object lf) {
LetterFreq letFreq = (LetterFreq)lf;
if (freq < letFreq.getFreq())
return -1;
else if (freq > letFreq.getFreq())
return +1;
else return 0; //The frequencies must be equal.
} //compareTo()
sort()
for AnalyzeFreq
:public void sort() {
java.util.Arrays.sort(freqArr);
} //sort()
AnalyzeFreq.main()
that uses sort()
:public static void main(String[] argv) {
AnalyzeFreq af = new AnalyzeFreq();
af.countLetters("Now is the time for all good students" +
" to study computer-related topics.");
af.sort();
af.printArray();
} //main()