⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 binarysrch.java

📁 many simple java programs like classic algorithems to do search and few data structure implimentatio
💻 JAVA
字号:
import java.io.*;
import java.util.Scanner;

class binarysrch
{
  public static boolean bin_search(int a[],int n,int key)
  {
    int first=0,last=n-1;
   
    //SORTING
    for(int i=0;i<n-1;i++)
       for(int j=i+1;j<n;j++)
         if(a[i]>a[j])
         {
           int temp=a[i];
               a[i]=a[j];
               a[j]=temp;
         }

    //SEARCH 
    while((last-first)>0)
    {
      int mid=(first+last)/2;
      if(a[mid]==key)
         return true;
      else
         if(a[mid]>key)
           last=mid-1;
         else
           first=mid+1;
    }
     return false;
   }
  
   public static void main(String args[])
   {
    int a[],n,key;
    Scanner s=new Scanner(System.in);
    
    System.out.print("Enter the number of elements:");
    n=s.nextInt();
    a=new int [n];

    System.out.println("Enter the elements:");
    for(int i=0;i<n;i++)
       a[i]=s.nextInt();
    
    System.out.print("Enter search key:");
      key=s.nextInt();
        
    if(bin_search(a,n,key))
      System.out.println("\nElement found! ");
    else
      System.out.println("\nElement not found!");  

   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -