3 .Write a computer program in Java that prompts the user for one number, n for
ID: 3598105 • Letter: 3
Question
3 .Write a computer program in Java that prompts the user for one number, n for the number of items in the array to sort, and create and sort 1000 arrays of this size timing the run to get an average time to sort an array of this size. Then do the following:
Initiate a variable running_time to 0
Create a for loop that iterates 1000 times.
In the body of the loop,
Create an array of n random integers
Get the time and set this to start-time. You will have to figure out what the appropriate command is in the programming language you are using to find the time
Use bubble sort to sort the array
Get the time and set this to end-time
Subtract start-time from end-time and add the result to total_time
Once the program has run, note
The number of items sorted
The average running time for each array (total_time/1000)
Repeat the process six times, using 50, 250 and 500 as the size of the array for each of the two algorithms.
4. Repeat 3 using selection sort.
5. Create a spreadsheet showing the results of 3 and 4 and create a graph to graphically represent the information. Show both sort algorithms on the same graph for comparison.
6. Write a one page document explaining the results, bearing in mind that both algorithms have a complexity of O(n^2) and what you know about complexity analysis. Use your knowledge of complexity analysis to explain your results.
Explanation / Answer
Simple Search or Linear Search
int[] a = { 3, 34, 5,91, 100}; // an array not containing duplicates
int target = 91; // the element to be searched
for( int i=0; i<a.length; i++) {
if(a[i]==target) {
System.out.println ( "Element found at index "+i);
break; // break should be omitted if the array contains duplicates
}
}
Binary Search
int[] a = {3, 7, 10, 15, 91, 110, 150}; // a sorted array not containing duplicates
int target = 91; // the element to be searched
int left = 0;
int middle;
int right = a.length - 1;
while (left <= right) {
middle = (left + right) / 2;
if (a[middle] == target) {
System.out.println("Element found at index " + middle);
break;
} else if (a[middle] < target) {
left = middle + 1;
} else if (a[middle] > target) {
right = middle - 1;
}
}
a[0] =a[minPos];
a[minPos]=a[0];
int temp = a[0];
a[0] = a[minPos];
a[minPos]= temp;
Bubble Sort
int[] a = {4, 85, 7, 1, 0, 36, -5, 48};
int minPos;
for (int i = 0; i < a.length; i++) {
minPos = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[minPos]) {
minPos = j;
}
}
int temp = a[0];
a[0] = a[minPos];
a[minPos] = temp;
}
int[] a = {4, 85, 7, 1, 0, 36, -5, 48};
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - I; j++) {
if (a[j + 1] < a[j]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.