数据结构与算法分析(java语言描述)之第一章

1.1
第一节的开头提出两个问题:设有一组N个数而要确定其中第K个最大者,称之为选择问题(selection problem)
第一种:把n个数放到array中,排个序

可以这样
int[] arr = new int[]{44, 132, 34, 67, 23, 434, 2, 4, 5, 24};
for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr.length - 1 - i; j++) {
        if (arr[j] > arr[j + 1]) {
            int val = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = val;
        }
    }
}
System.out.println(Arrays.toString(arr));
这样
Arrays.sort(arr,new Decrease());
System.out.println(Arrays.toString(arr));
或者是这样
System.out.println(Arrays.toString(Arrays.stream(arr).sorted(new Decrease()).toArray()));
用二进制搜索找到第几个最大者
Arrays.sort();升序使用没问题,降序就不行后来看了API如下
the specified array for the specified object using the binary
search algorithm
The range must be sorted into **ascending order**
采用的是二进制搜索算法,只支持升序
另外Arrays.sort();只支持asc,想要降序需要重写
static class Decrease implements Comparator<Integer> {
    /**
     * 重写compare方法,默认从小到大排序,更改后从大到小排序
     */
    @Override
    public int compare(Integer o1, Integer o2) {
        if (o1 > o2) {
            return -1;
        }
        if (o1 < o2) {
            return 1;
        }
        return 0;
    }
}
System.out.println(Arrays.binarySearch( arr,434));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值