Finish the exercises from last week than attempt the Using Arrays exercises in the example problems below.
Here are some hints about how to do exercise 2 from last week. Suppose we have an array of some fixed length, say 10. Java initialises all the elements to zero. Now let’s assume that we only want to store positive numbers (i.e. greater than 0) in the array. In that case, it’s convenient to treat zero as meaning an array cell is empty. Initially, the array will look like this:
0 0 0 0 0 0 0 0 0 0
Now let’s insert the number 5. All we have to do is look for the first empty position (i.e. contains 0) and replace it with 5:ow let’s insert the number 5. All we have to do is look for the first empty position (i.e. contains 0) and replace it with 5:
5 0 0 0 0 0 0 0 0 0
Now let’s insert 4. It goes before 5, so we have to shift 5 down one place and insert 4 where 5 was:
4 5 0 0 0 0 0 0 0 0
Now let’s insert 3. It goes before 4, so we have to shift 4 and 5 down one place and insert 3 where 5 was:
3 4 5 0 0 0 0 0 0 0
Inserting 6 is easier because it is larger than any of the existing entries, so it will go into the next empty spot:
3 4 5 6 0 0 0 0 0 0
What happens when the array fills up? What should you do?
Comments are closed.