What would a solution to these methods look like? /** * A comparative time test
ID: 3605489 • Letter: W
Question
What would a solution to these methods look like?
/**
* A comparative time test for linear search versus binary search on
* sorted data. Uses System.nanoTime() to find how much time each search
* takes to finish on the passed data and key.
* @param data - Data set to be tested.
* @param key - Value to search for in the data set.
*
*/
public static void linearVsBinaryTest(int[] data, int key)
{
}
/**
* A comparative time test for Merge Sort versus Tim Sort.
* Uses System.nanoTime() to find how much time each sort
* takes to finish on the passed data.
* @param data - Data set to be tested.
*/
public static void mergeVsTimTest(int[] data)
{
}
Explanation / Answer
import java.util.Arrays;
import java.util.Scanner;
public class search {
public static void main(String args[]) {
int[] num = new int[20];
for (int i = 0; i < num.length; i++) {
num[i] = (int) (Math.random() * 101);
}
System.out.println("A list of 20 random intergers with 0 - 100");
System.out.println(Arrays.toString(num));
for (int j = 1; j < num.length; j++) {
for (int k = 0; k < num.length - 1; k++) {
if (num[k] < num[k + 1]) {
int hold = num[k + 1];
num[k + 1] = num[k];
num[k] = hold;
}
}
}
System.out.println("Array in descending order");
System.out.println(Arrays.toString(num));
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to search: ");
int num2 = input.nextInt();
int loop = 0;
for ( int cnt = 0; cnt < num.length; cnt++ )
{
if ( num[cnt] == num2 )
{
loop = cnt;
System.out.println(num2+ " found");
}
}
System.out.println("Linear search - "+loop+ " loop(s)");
int loop2 = 0;
int low = 0; // low element subscript
int high = num.length - 1; // high element subscript
int middle; // middle element subscript
while ( low <= high ) {
middle = ( low + high ) / 2;
if ( num2 == num[ middle ] ) {
}
else if ( num2 > num[ middle ] )
{
low = middle +1;
loop2++;
}
else{
high = middle - 1;
loop2++;
}
}
System.out.println("Binary search - "+loop2+ " loop(s)");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.