Arrays
Due 11:59 Wednesday October 20
-
Using my solution
to the Histogram Program (PS2, Q3), rewrite the program so that it uses a
single, ten-element array instead of the ten instance variables.
Hint: do not use a bunch of conditionals to determine which bin
to increment. Instead, compute the array index directly using
integer division. The initialization of the array and the displaying of
the histogram should be done using a loop.
Solution.
-
Write a static method called
BubbleSort that takes an arbitrary-size array as an argument, and
sorts it from smallest to largest, using the "bubble sort" algorithm,
which works like this (where s is the size of the array):
 |
Look at the first two elements. |
 |
If the first is less than the 2nd, leave them alone;
otherwise, swap them. |
 |
Now look at the 2nd and 3rd elements, and do the same thing. |
 |
Repeat until you reach the end of the array; i.e. do this
s-1 times. |
 |
Now, repeat this entire process s-1 times. |
For example, suppose the array has 4 elements, and it
initially has the values: 4 3 2 1. Here are the values of the array
after each swapping of values. Note that the array is fully sorted after
7 steps, but the algorithm goes through all 9 steps anyway.
Start: 4 3 2 1
3 4 2 1
3 2 4 1
3 2 1 4
2 3 1 4
2 1 3 4
2 1 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Test your program by generating some arrays initialized to
random values. In fact, try it on some really
large arrays. You only have to display the original array and its sorted
version (i.e. you don't have to display each step as shown above).
Solution.
|