二分搜尋演算法

來源:互聯網
上載者:User

標籤:二分搜尋   java   演算法   

二分搜尋演算法

題目:設 a [ 0 : n - 1 ] 是一個已排好序的數組。請改寫二分搜尋演算法,使得當搜尋元素 x 不在數組中時,返回小於 x 的最大元素的位置 i 和大於 x 的最小元素位置 j 。當搜尋元素在數組中時, i 和j相同,均為 x 在數組中的位置。並對自己的程式進行複雜性分析。

import java.util.Arrays;import java.util.Scanner;public class Main {static int x;// 需要尋找的資料// 形參i,j是數組下標,arr是原數組,answer是儲存答案的數組static void getij(int i, int j, int[] arr, int[] answer) {if (i > j) {// x不在數組中的情況answer[0] = j;answer[1] = i;return;}int len = j - i + 1;// 加不加1都可以if (x == arr[len / 2 + i]) {// x在數組中的情況Arrays.fill(answer, len / 2 + i);// java api 方法,作用是將數組answer裡的元素都賦值為len/2+1} else if (x < arr[len / 2 + i]) {getij(i, len / 2 + i - 1, arr, answer);} else {getij(len / 2 + i + 1, j, arr, answer);}}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int n = scanner.nextInt();int[] arr = new int[n];for (int i = 0; i < n; i++) {arr[i] = scanner.nextInt();}x = scanner.nextInt();// 答案 儲存的是數組下標 i = answer[0]; j = answer[1]int[] answer = new int[2];getij(0, n - 1, arr, answer);// 0,n-1都是數組的下標System.out.println(answer[0] + " " + answer[1]);}scanner.close();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.