Arrays.binarySearch()

來源:互聯網
上載者:User

今天學的頭疼,有些地方還是要自己深入的琢磨琢磨。雖然java是物件導向的,過程也是要稍微掌握點的。

 

 在使用這個方法的時候,譬如:

static int binarySearch(int[] a, int key)
          Searches the specified array of ints for the specified value using the binary search algorithm.

 

import study.Arrays2;
import java.util.*;

public class ArraySearching {
 public static void main(String[] args) {
  int[] a = new int[5];
  Arrays2.RandIntGenerator gen = new Arrays2.RandIntGenerator(1000);
  Arrays2.fill(a,gen);
  Arrays.sort(a);
  System.out.println("Sorted array: " + Arrays2.toString(a));
  while(true) {
   int r = gen.next();
   int location = Arrays.binarySearch(a,r);
   System.out.println(r);
   System.out.println(location);
   if(location >= 0) {
    System.out.println("Location of " + r + " is " + location + ", a[" + location + "] = " + a[location]);
    break;
   }
  }
 }
}

 

如果數組a中如果沒有key,則傳回值為某個負值,表示為了保持排序狀態,此目標元素應該插入的位置“-(插入點)-1”;如果找到了key,則返回key所在元素下標。

 

插入點是指,第一個大於尋找對象的元素在數組中的位置,如果數組所有元素都小於要尋找的對象,插入點就等於a.size().

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.