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

OOP LAB MANUAL

Uploaded by

santhikala
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)
0 views

OOP LAB MANUAL

Uploaded by

santhikala
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/ 4

1.

Solve problem using sequential search,binary search and quadratic sorting algorithms

A.Sequential search

public class ArraySearcher

/** Finds the index of a value in an array of integers.

* @param elements an array containing the items to be searched.

* @param target the item to be found in elements.

* @return an index of target in elements if found; -1 otherwise.

*/

public static int sequentialSearch(int[] elements, int target)

for (int j = 0; j < elements.length; j++)

if (elements[j] == target)

return j;

return -1;

public static void main(String[] args)

int[] numArray = {3, -2, 9, 38, -23};

System.out.println("Tests of sequentialSearch");

System.out.println(sequentialSearch(numArray,3));

System.out.println(sequentialSearch(numArray,9));

System.out.println(sequentialSearch(numArray,-23));
System.out.println(sequentialSearch(numArray,99));

Output:

Tests of sequentialSearch
0
2
4
-1

B.Binary search

public class SearchTest

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

int left = 0;

int right = elements.length - 1;

while (left <= right)

int middle = (left + right) / 2;

if (target < elements[middle])

right = middle - 1;

else if (target > elements[middle])

left = middle + 1;
}

else {

return middle;

return -1;

public static void main(String[] args)

int[] arr1 = {-20, 3, 15, 81, 432};

// test when the target is in the middle

int index = binarySearch(arr1,15);

System.out.println(index);

// test when the target is the first item in the array

index = binarySearch(arr1,-20);

System.out.println(index);

// test when the target is in the array - last

index = binarySearch(arr1,432);

System.out.println(index);

// test when the target is not in the array

index = binarySearch(arr1,53);

System.out.println(index);

}
Output:

2
0
4
-1

You might also like