java折半查找

折半查找操作:使用折半查找有序数组中元素。找到返回索引(在数组中的位置),不存在输出-1。
分析:折半查找的前提是数组有序。
假如有一组数为3,12,24,36,55,68,75,88要查给定的值24.
可设三个变量front,mid,end分别指向数据的上界,中间和下界,mid=(front+end)/2.
(1)开始令front=0(指向3),end=7(指向88),则mid=3(指向36)。因为mid>x,故应在前半段中查找。
(2)令新的end=mid-1=2,而front=0不变,则新的mid=1。此时x>mid,故确定应在后半段中查找。
(3)令新的front=mid+1=2,而end=2不变,则新mid=2,此时a[mid]=x,查找成功。
(4)如要查找的数不是数列中的数,例如x=25,当第三次判断时,x>a[mid],按以上规律,令front=mid+1,即front=3,出现front>end的情况,表示查找不成功。

import java.util.Scanner;
public class SuZu4 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int[] a = {3, 12, 24, 36, 55, 68, 75, 88};
        System.out.print("请输入要查找的数:");
        int n =sc.nextInt();

        int front = 0;
        int end = a.length - 1;
        int mid = (front + end) / 2;
        do {
            int jg;
            if (a[mid] > n) {
                end = mid - 1;
                mid = (front + end) / 2;
                if (end < front) {
                    System.out.println("查找不成功");
                    return;
                }
            } else if (n > a[mid]) {
                front = mid + 1;
                mid = (front + end) / 2;
                if (front > end) {
                    System.out.println("查找不成功");
                    return;
                }
            }
        } while (a[mid] != n);
        System.out.println(mid);
    }
}

 折半查找递归操作


import java.util.Scanner;

public class SuZu62 {
    public static void main(String[] args) {
        int[] a = {3, 12, 24, 36, 55, 68, 75, 88};
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要查找的数:");
        int n = sc.nextInt();
        int s = seek(a, 0, a.length - 1, n);
        System.out.println(s);

    }

    public static int seek(int[] arr, int front, int end, int n) {
        int mid = (end + front) / 2;
        if (front <= end) {
            if (arr[mid] == n) {
                return mid;
            } else if (arr[mid] > n) {
                return seek(arr, front, mid - 1, n);
            } else {
                return seek(arr, mid + 1, end, n);
            }
        } else {
            return -1;
        }
    }
}

结果如上


版权声明:本文为weixin_52923290原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。