二进制搜索法 java
binary search in Java. You can ask your doubts if you find difficulty to understand the program.
二进制搜索的程序。 如果您难以理解程序,可以提出疑问。
二进制搜索Java程序 ( Java Program for Binary Search)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import java.util.Scanner;
class BinarySearch
{
public static void main(String ar[])
{ int i,mid,first,last,x,n,flag=0;
Scanner sc=new Scanner(System.in);
System.out.println("nEnter number of elements:");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("nEnter elements of array:");
for(i=0;i<n;++i)
a[i]=sc.nextInt();
System.out.println("nEnter element to search:");
x=sc.nextInt();
first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(a[mid]>x)
last=mid-1;
else
if(a[mid]<x)
first=mid+1;
else
{
flag=1;
System.out.println("nelement found");
break;
}
}
if(flag==0)
System.out.println("nelement not found");
}
}
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import java . util . Scanner ;
class BinarySearch
{
public static void main ( String ar [ ] )
{ int i , mid , first , last , x , n , flag = 0 ;
Scanner sc = new Scanner ( System . in ) ;
System . out . println ( "nEnter number of elements:" ) ;
n = sc . nextInt ( ) ;
int a [ ] = new int [ n ] ;
System . out . println ( "nEnter elements of array:" ) ;
for ( i = 0 ; i < n ; ++ i )
a [ i ] = sc . nextInt ( ) ;
System . out . println ( "nEnter element to search:" ) ;
x = sc . nextInt ( ) ;
first = 0 ;
last = n - 1 ;
while ( first <= last )
{
mid = ( first + last ) / 2 ;
if ( a [ mid ] > x )
last = mid - 1 ;
else
if ( a [ mid ] < x )
first = mid + 1 ;
else
{
flag = 1 ;
System . out . println ( "nelement found" ) ;
break ;
}
}
if ( flag == 0 )
System . out . println ( "nelement not found" ) ;
}
}
|
翻译自: https://www.thecrazyprogrammer.com/2015/05/program-for-binary-search-in-java.html
二进制搜索法 java