हिंदी

Fill an array (type int, size n). Perform Linear Search; Binary Search.

Advertisements
Advertisements

प्रश्न

Fill an array (type int, size n).

Perform Linear Search; Binary Search.

कोड लेखन
Advertisements

उत्तर

import java.util.Scanner;
import java.util.Arrays;
public class EasySearch 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);        
        System.out.print("Enter size n: ");
        int n = sc.nextInt();
        int R[] = new int[n];        
        System.out.println("Enter elements:");
        for (int i = 0; i < n; i++) 
        {
            R[i] = sc.nextInt();
        }        
        System.out.print("Enter target to search: ");
        int target = sc.nextInt();        
        int li = -1;
        for (int i = 0; i < n; i++) 
        {
            if (R[i] == target) 
            {
                li = i;
                break;
            }
        }
        System.out.println("Linear Search Index: " + li);        
        int low = 0, high = n - 1, bi = -1;        
        while (low <= high)
        {
            int mid = (low + high) / 2;
            if (R[mid] == target) 
            {
                bi = mid;
                break;
            } 
            else if (R[mid] < target) 
            {
                low = mid + 1;
            } 
            else 
            {
                high = mid - 1;
            }
        }
        System.out.println("Binary Search Index (after sorting): " + bi);
    }
}

Output:

Enter size n : 5 

Enter elements : 

85 12 44 60 37

Enter target to search : 60

Linear Search Index : 3 Binary Search Index

shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 11: Programs Overall - Arrays [पृष्ठ २५२]

APPEARS IN

रुपा पंडित Computer Applications [English] Class 10 ICSE
अध्याय 11 Programs Overall
Arrays | Q 7. | पृष्ठ २५२
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×