0% found this document useful (0 votes)
11 views

LAB 2 and 1

Uploaded by

hassamkiani66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

LAB 2 and 1

Uploaded by

hassamkiani66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

1-Oct-2024

Lab1: Ex1. Calculate the elapsed time of Linear search and Binary Search.
Code:
public class App {
public static void main(String[] args) {
int[] num = {1, 2, 3, 5, 6, 7};

long startTime = System.nanoTime();


int foundBinary = binarySearch(num, 3);

if (foundBinary == -1) {
System.out.println("Not Found!");
} else {
System.out.println("Found at Index " + foundBinary);
}

long stopTime = System.nanoTime();


long elapsedTime = stopTime - startTime;
System.out.println("Binary: "+elapsedTime + " ns");

long startTime1 = System.nanoTime();


int linearFound = linearSearch(num, 5);
if (linearFound == -1) {
System.out.println("Not Found!");
} else {
System.out.println("Found at Index " + linearFound);
}

long stopTime1 = System.nanoTime();


long elapsedTime1 = stopTime1 - startTime1;
System.out.println("Linear :"+elapsedTime1 + " ms");
}

public static int linearSearch(int[] num, int target) {


for (int i = 0; i < num.length; i++) {
if (num[i] == target) {
return i;
}
}
return -1;
}

public static int binarySearch(int[] num, int target) {


int left = 0;
int right = num.length - 1;

while (left <= right) {


int middle = left + (right - left) / 2; // Corrected calculation of middle
if (num[middle] == target) {
return middle;
}
if (num[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
}

Output:

Lab2: Ex2.Consider the below code for interative binary search. Run the code
and write down the output. And also explain its working.
class BinarySearchDemo {
static Object[] a = { 10, 20, 30, 40, 50, 60, 70, 80 };
static Object key = 50;

public static void main(String args[]) {


if (binarySearch())
System.out.println(key + " found in the list");
else
System.out.println(key + " not found in the list");
}

static boolean binarySearch() {


int c, mid, low = 0, high = a.length - 1;
while (low <= high) {
mid = (low + high) / 2;
c = ((Comparable) key).compareTo(a[mid]);
if (c < 0)
high = mid - 1;
else if (c > 0)
low = mid + 1;
else
return true;
}
return false;
}
}

Output:

You might also like