Java Reference
In-Depth Information
Write a test program that reads in ten integers, invokes the method, and displays
the result. Here is the sample run of the program:
Enter ten numbers:
The distinct numbers are: 1 2 3 6 4 5
1 2 3 2 1 6 3 4 5 2
6.16
( Execution time ) Write a program that randomly generates an array of 100,000
integers and a key. Estimate the execution time of invoking the linearSearch
method in Listing 6.6. Sort the array and estimate the execution time of invoking
the binarySearch method in Listing 6.7. You can use the following code tem-
plate to obtain the execution time:
long startTime = System.currentTimeMillis();
perform the task;
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
**6.17
( Sort students ) Write a program that prompts the user to enter the number of stu-
dents, the students' names, and their scores, and prints student names in decreas-
ing order of their scores.
**6.18
( Bubble sort ) Write a sort method that uses the bubble-sort algorithm. The bubble-
sort algorithm makes several passes through the array. On each pass, successive
neighboring pairs are compared. If a pair is not in order, its values are swapped;
otherwise, the values remain unchanged. The technique is called a bubble sort or
sinking sort because the smaller values gradually “bubble” their way to the top and
the larger values “sink” to the bottom. Write a test program that reads in ten double
numbers, invokes the method, and displays the sorted numbers.
**6.19
( Sorted? ) Write the following method that returns true if the list is already sorted
in increasing order.
public static boolean isSorted( int [] list)
Write a test program that prompts the user to enter a list and displays whether the
list is sorted or not. Here is a sample run. Note that the first number in the input
indicates the number of the elements in the list.
Enter list:
The list is not sorted
8 10 1 5 16 61 9 11 1
Enter list:
The list is already sorted
10 1 1 3 4 4 5 7 9 11 21
*6.20
( Revise selection sort ) In Section 6.11.1, you used selection sort to sort an array.
The selection-sort method repeatedly finds the smallest number in the current
array and swaps it with the first. Rewrite this program by finding the largest num-
ber and swapping it with the last. Write a test program that reads in ten double
numbers, invokes the method, and displays the sorted numbers.
***6.21
( Game: bean machine ) The bean machine, also known as a quincunx or the Gal-
ton box, is a device for statistics experiments named after English scientist Sir
Francis Galton. It consists of an upright board with evenly spaced nails (or pegs)
in a triangular form, as shown in Figure 6.15.
 
 
Search WWH ::




Custom Search