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));