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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 預(yù)備知識 【來自維基百科】二叉查找樹(英語:Binary Search Tree),也稱二叉搜索樹、有序二叉樹(英...
- Given a target integer T and an integer array A, A is sor...
- 解題思路 : recursive 作業(yè)順序: 往左檢查 left child 只要有符合 > k1 的 node ...
- 問題:Given the root node of a binary search tree (BST) and ...
- 文章作者:Tyan博客:noahsnail.com | CSDN | 簡書 1. Description 2. S...