Collections的排序:
static<T> boolean addAll(Collection<?super T> c , T...elements)---将所有指定元素添加到指定的collection中---感觉有了addAll(),不用再一个个添加了
static void reverse(List list)---反转
static void shuffle(List list)---随机排序(“洗牌”);
static void sort(List list)---按自然顺序排序
static void swap(List list , int i , int j )---将指定集合中i处元素和j处元素进行交换
public class Example26{
public void static main(String[] args){
ArrayList list = new ArrayList();
Collections.addAll(list,"feriosa","max","nux");
Collections.reverse(list);
Collections.shuffle(list);
Collections..sort(list);
Collections.swap(list,0,1);
}
}
public int binarySearch(int[] arr, int x) {
int max = arr.length -1 ;
int min = 0 ;
int mid =(min + max) / 2 ;
while(min != max){
if(arr[mid] > x){
max = mid -1 ;
}else if(arr[mid]< x){
min = mid +1 ;
}else if (max < min ){
return -1;
}
mid = (max +min)/2;
}
return mid;
}
或者:
public int binarySearch(int[] arr , int x ){
int max = arr.length -1 ;
int min = 0 ;
int mid ;
while(min < max){
mid = (min +max)>>1;
if(arr[mid] > x ){
max = mid -1 ;
}else if (arr[mid] < x){
min = mid +1 ;
}else{
return mid;
}
}
return -1; //这种情况是min>= max,直接方法-1即可
}
好现在再来看Arrays类的常有静态方法:
Arrays.sort(int[] arr)---排序(类似选择法或者冒泡法)
Arrays.binarySearch(Object[] a, Object key)---查询(类似二分法)
Arrays.copyOfRange(int[] original, int from, int to)---拷贝元素(在不破环原数组的情况下)
Arrays.fill(Object[] a, Object val)---填充元素
Arrays.toString(int[] arr)---将数组转化成为字符串