Untitled
unknown
java
3 years ago
2.0 kB
11
Indexable
package Labs.Assignment7;
import java.util.*;
public class QuestionSevenPointSixteen
{
public static int linearSearch(int[] numbers, int num)
{
for (int i = 0; i < numbers.length; i++)
{
if (num == numbers[i])
{
return i;
}
}
return -1;
}
public static int binarySearch(int[] numbers, int num)
{
int low = 0;
int high = numbers.length - 1;
while (high >= low)
{
int mid = (low + high) / 2;
if (num < mid)
{
high = mid - 1;
}
else if (num == mid)
{
return mid;
}
else
{
low = mid + 1;
}
}
return -low -1;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int arrayLength = 100000000;
int[] numbers = new int[arrayLength];
int nums[] = {25000000,50000000,75000000,100000000};
for(int i = 0; i<arrayLength;i++)
{
numbers[i] = i+1;
}
System.out.println(numbers[arrayLength-1]);
for(int i = 0; i<nums.length;i++)
{
int num = nums[i];
long startTime = System.nanoTime();
linearSearch(numbers, num);
long endTime = System.nanoTime();
long executionTime = endTime - startTime;
System.out.printf("Execution time of invoking the linearSearch for %d in nanoseconds is : %d Nano-Seconds",num,executionTime);
System.out.println();
startTime = System.currentTimeMillis();
binarySearch(numbers, num);
long endTime2 = System.currentTimeMillis();
long executionTime2 = endTime2 - startTime;
System.out.printf("Execution time of invoking the binarySearch for %d in nanoseconds is : %d Nano-Seconds",num,executionTime2);
System.out.println();
}
}
}
Editor is loading...