- Loops within loops are particularly hard:
public void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
for (int j = 0; j < nums.length - i - 1; ++j) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
}
- The relationship between "i" and "j" is hard to understand
- The "nesting" abstraction is tricky; student code could look like this:
public void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
}
for (int j = 0; j < nums.length; ++j) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
- If you assign a nested loop assignment, it might help to give the
students the algorithm in English; the student task is reduced to translating
English into Java
For each element i of the array
For each element j of the array, stopping at size - i
If j and its successor are out of order, swap them