package Search;
import java.util.Scanner;
public class BinarySearch {
static final int N=15;
public static void quick(int[] arr, int start, int end) {
int low = start;
int high = end;
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
if (end <= start)
{
return;
}
quick(arr, start, low - 1);
quick(arr, low + 1, end);
}
static int binarySearch(int a[],int len,int key)
{
int mid,low,high;
low=0;
high=len;
mid=(int)(low+high)/2;
while(low<=high)
{
if(a[mid]==key)
{
return mid;
}
else if(a[mid]<key)
{
low=mid++;
}
else
high=mid--;
}
return -1;
}
public static void main(String[] args)
{
int x,n,i;
int[] array = new int[N];
for(i=0;i<N;i++)
{
array[i]=(int)(100+Math.random()*(100+1));
}
System.out.println("the original number is :");
for(i=0;i<N;i++)
{
System.out.println(array[i]);
}
quick(array,0,N-1);
System.out.println("the sorted array is :");
for(i=0;i<N;i++)
{
System.out.print(array[i]+"\n");
}
System.out.println("enter the number to look for");
Scanner input=new Scanner(System.in);
x=input.nextInt();
n=binarySearch(array,N,x);
if (n<0)
{
System.out.println("number not found");
}
else
{
System.out.println("the index of number is :"+(n+1));
}
}
}
Binary Search
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 预备知识 【来自维基百科】二叉查找树(英语:Binary Search Tree),也称二叉搜索树、有序二叉树(英...
- Given a target integer T and an integer array A, A is sor...
- 解題思路 : recursive 作業順序: 往左檢查 left child 只要有符合 > k1 的 node ...
- 问题:Given the root node of a binary search tree (BST) and ...
- 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. S...