Posts

Showing posts with the label searching

Binary Search using Java

Image
It is a technique to search an element in sorted array. In this type of search half of the array is ignored just after one comparison. Each time required element is compared with middle element of the array and range is decided . Best Case Performance :  O(1) Average Case Performance : O(log n) Worst Case Performance : O(log n) Demo Output: The Program import java.util.Scanner; public class BinarySearch1 { public static void main(String args[]) { int i, first=0, last, mid, no, element; Scanner s = new Scanner(System.in); System.out.println("\n How many elements:"); no= s.nextInt(); int arr[]= new int[no]; System.out.println("\n Enter the elements:"); for (i = 0; i < no; i++) arr[i] = s.nextInt(); System.out.println("\n Enter the element to be searched:"); element = s.nextInt(); last = no - 1; mid = (first + last)/2; while( first <= last ) { if ...

Linear search

The following program takes a number as an input and checks whether that number is present in a group of elements or not. It takes linear time to execute. The program is implemented using c. #include<stdio.h> int main() { int n; printf("Enter number of elements of the group : "); scanf("%d",&n); int a[n],m,i; for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter a element for searching : "); scanf("%d",&m); for(i=0;i<n;i++) { if(m==a[i]) { printf("%d found in %d position.",m,i+1); break; } } return 0; } Description : In the above program the group of elements are stored using array. Then the input number is compared with all the elements in the array. If input number and element of array are equal, then it prints found and terminates. Output: Enter number of elements : 5 9 6 7 2 8 Enter ...