二分查找之java实现

来源:互联网 发布:ubuntu 16.04更新源 编辑:程序博客网 时间:2024/05/07 16:05

二分查找:又称折半查找,是在有序数组中进行查找。

分为两种:递归方法和非递归方法。

过程:

1、确定数组的中间位置mid=(low/high)/2

2、用要查找的数值与中间值比较:
若相等,则查找成功
若小于,则继续在左半部分查找
若大于,则继续在右半部分查找
3、重复步骤直到找到为止,未找到表明不存在
特点:
1、每次查找都比上一次查找少一半,时间复杂度为O(logn)。

2、必须在有序数组中进行。


递归方法核心代码:

public static int binSearch1(int arr[], int start, int end, int key){int mid = (end + start) / 2;           if (arr[mid] == key) {               return mid;           }           if (start >= end) {               return -1;           }else if (key > arr[mid]) {           //右边递归调用            return binSearch1(arr, mid + 1, end, key);           }else if (key < arr[mid]) {           //左边递归调用            return binSearch1(arr, start, mid - 1, key);           }           return -1; }

递归方法完整代码:

public class BinarySearch1 {public static void main(String[] args){int arr[] = {0,1,2,3,4,5,6,7,8,9};System.out.print("请输入要查找的数:");Scanner sc = new Scanner(System.in);System.out.print("位置坐标为:"+binSearch1(arr, 0, arr.length-1, sc.nextInt()));}public static int binSearch1(int arr[], int start, int end, int key){int mid = (end + start) / 2;           if (arr[mid] == key) {               return mid;           }           if (start >= end) {               return -1;           }else if (key > arr[mid]) {           //右边递归调用            return binSearch1(arr, mid + 1, end, key);           }else if (key < arr[mid]) {           //左边递归调用            return binSearch1(arr, start, mid - 1, key);           }           return -1; }}

输入内容及程序运行结果:

请输入要查找的数:8
位置坐标为:8


非递归方法完整代码:

public class BinarySearch2 {public static void main(String[] args){int arr[] = {0,1,2,3,4,5,6,7,8,9};/* * 通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入, * 直到敲回车键结束,把所输入的内容传给Scanner,作为扫描对象。 * 如果要获取输入的内容,则只需要调用Scanner的nextLine()方法即可。 */System.out.print("请输入要查找的数:");Scanner sc = new Scanner(System.in);int key = sc.nextInt();int start = 0, end = 9;int mid = (start+end) / 2;while(arr[mid] != key && start <= end) {if(arr[mid] < key)start = mid + 1;elseend = mid - 1;mid = (start+end) / 2;}if(arr[mid] == key)System.out.println("位置坐标为:"+mid);elseSystem.out.println("not found");}}

输入内容及程序运行结果:

请输入要查找的数:100
not found


转载请标明出处,原文地址:http://write.blog.csdn.net/postedit

0 0