• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
洗尽铅华终究染懵懂
博客园    首页    新随笔    联系   管理    订阅  订阅

sort()方法和binarySearch()方法

JAVA语言提供了两种方法,sort()方法和 binarySearch()方法,可以方便地对数组进行排序和搜索。

sort()方法使用改进的快速排序算法将数组中的元素进行升序排列,而 binarySearch()方法在一个数组中搜索某个指定值。

因为 binarySearch()方法使用二进制的搜索方法,要求数组是有序数组。因此在实际使用时,调用 binarySearch()方法之前通常先调用 sort()方法。使用导入语句 import java.util.*; 。

关于 binarySearch()的返回值:

如果目标数包含在数组中,则返回搜索键的索引即数组元素下标;否则返回 (-(插入点) - 1)。
插入点被定义为将键插入数组的那一点:即第一个大于此数的元素索引,如果数组中的所有元素都小于指定的键,则为 a.length。

注意:   这保证了当且仅当此键被找到时,返回的值将 >= 0。搜索
          否则返回 (-(插入点) - 1)这句话要注意:要是查询的的值小于数组里面
          的最小值那么结果(-(0)-1结果就是-1),如果查询的 值大于数组里面的

          最大值。那么结果就是(-(它的索引值)-1结果就是-(1+索引值))。

 1 import java.util.*;
 2 public class JAVA1{
 3     public static void main(String[] args){
 4         Scanner in=new Scanner(System.in);
 5         System.out.println("Enter the number of array values:");
 6         int n=in.nextInt();
 7         int[] arr=new int[n];
 8         for(int i=0;i<n;i++){
 9             System.out.println("Enter element "+(i+1)+":");
10             arr[i]=in.nextInt();
11         }
12         Arrays.sort(arr);
13         System.out.print("The values in sorts order are:");
14         boolean first=true;
15         for(int i=0;i<arr.length;i++){
16             if(first){
17                 first=false;
18             }else{
19                 System.out.print(" ");
20             }
21             System.out.print(arr[i]);
22         }
23         System.out.println();
24         System.out.println("Enter the item you are searching for:");
25         int h=in.nextInt();
26         int location=Arrays.binarySearch(arr,h);
27         if(location>0){
28             System.out.println("This item is at location "+(location+1)+" in the sorted arry.");
29         }else{
30             System.out.println("This item is not in the list.");
31         }
32     }        
33 }
posted @ 2015-08-07 15:53  洗尽铅华终究染懵懂  阅读(669)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3