二分查找
查找的数据必须是有序排列的,Collections所提供的方法sort是按从小到大排列的,所以先默认顺序从小到大。
查找思想:先找到一组数据的头(start)和尾(end),每次查找时先看看数据的正中间数字(center)是否大于所需查找数据
如果小于说明数据在头和中间数字中间,这时把尾部改为中间数字-1位就行
大于的话就在中间和结尾之间,这时把开头得数字该为中间数字+1位就行
如果中间数字等于了需要查找的数据,说明已经找到了。
重复以上操作,如果结尾的下标大于了开头的下标,说明此组数据没有所需结果。
代码如下
public static boolean getNeber2(ArrayList<Integer> arrayList,int neber) {
Collections.sort(arrayList);//使此组数据有序
System.out.println(arrayList);
int start=0;//获取初始开头下标
int end=arrayList.size()-1;//获取初始结尾下标
int center;
while (start<=end) {//结束条件end下标>start下标
center=(start+end)/2;//获取中间位置的下标
if(neber<arrayList.get(center)) {//和目标数字找找
end=center-1;//小于时在中间位置左边,改下尾部位置,-1是因为center与目标间接判断了,不用管center
}else if(neber>arrayList.get(center)) { //
start=center+1; // 大于时,目标在center右边 ,改个开头
}else {//不大于中间数字,也不小于,只能是等于了,所以返回center下标就是
System.out.println("有下标是"+center);
return true;
}
} //如果循环完毕都没找到,那就是没有这个数字
return false;
}
快速排序:
1 首先随便在数组中找个值作为基准,一般找个最右边或最左边就挺好的,咱选最左的数字
2 要从基准相反的地方开始靠近,这样不会漏数字
从数组的最右和最左用下标朝中间靠近,从基准的另一个方向开始(此时为最右边的开始)靠近最好,接着找到第一个比基准小的数字,停下
3然后从左边开始靠近,找到第一个比基准大的,停下
4这时若两者不指在同一位置,将两位置数字交换, 重复之前操作
5若在同一个位置,将此数字与基准交换,此时基准数字已经有序,
6将其左边的数据,与右边的数据重复以上操作
7直到没有下标可移动,则排序有序
public class Quick {
public static void main(String[] args) {
Integer[] a =new Integer[] {1,34,45,63,24,42,456,563,63,25};
sort(a);
for (Integer integer : a) {
System.out.println(integer);
}
}
public static void sort(Integer[] a) {
// Collections.shuffle(a); 可以考虑让数组更混乱
partition(a, 0,a.length-1);
}
public static void partition(Integer[] a,int start,int end) {//切分
if(start>=end) {
return;//两个相遇说明为单一数组,已经排好
}
int i=start;//最左边为基准
int j=end;
int pivot=a[start];//最左边位置数字
while (i<j) {
while (a[j]>=pivot&&i<j) {//j左移
--j;
}
while (a[i]<=pivot&&i<j) {//i右移
++i;
}
if(i<j) { //找到了两个数字左边的大于基准,右边的小于基准
int tmp=a[i];
a[i]=a[j];
a[j]=tmp;
} //交换这两个数字
}//此循环结束后i和j指在同一个位置
a[start]=a[i];//把此位置值和基准交换
a[i]=pivot;//把此位置值和基准交换
partition(a, start, i-1);//操作相遇左边的数字
partition(a, i+1, end);//操作相遇位置右边的数字
}
}