sort()方法和binarySearch()方法

本文介绍Java中的排序和搜索方法,包括sort()方法实现快速排序,binarySearch()方法用于有序数组的搜索。通过示例代码展示了如何使用这两个方法,并解释了binarySearch()方法返回值的意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

转载于:https://www.cnblogs.com/MC-1996/p/4711045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值