COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Sorting and Searching Algorithms SelectionSort Program BinarySearch Program QuickSort Program HardwareStore Program HardwareStore Comparable Objects Program



BinarySearch Program


Description

This program uses the binary search algorithm to search a desired value in a sorted array.

Associated Concepts:

Binary Search

Algorithm:

main method:

Create an array with random integers.

Print the unsorted array elements.

Call the method selectionSort() to sort the array, and pass the array as the argument.

Print the sorted array elements.

Input an integer as the desired value to search.

Call the method binarySearch() and pass the array, the left most index, the right most index, and the desired value as the arguments.

If the desired value is found in the array, print its index.

Otherwise, print a message to indicate that it is not found.

binarySearch method definition:

Calculate the index of the element in the middle of the array.

Compare key and a[middle]

If key == a[middle],

     found it, set the foundIndex

Else if key < a[middle],

     A further search is conducted among the left of a[middle] if the sub-array has more than one element.

Else,

     A further search is conducted among the right of a[middle] if the sub-array has more than one element.

Return the foundIndex.

Source Code



Sample Run



Video