二分法
public class MyArrays{
public static void main(String[] args){
int[] a = {1,3,4,5,7,8,9,10,23,25,29};
// 取得23在數組中的位置
int flag = 53;
int index = binarySearch(a,flag);
if(index != -1){
System.out.println("取得數組中"+flag+" 的下標爲:" + index);
} else {
System.out.println("該值:"+flag+" 在數組中不存在 !");
} }
// 採用二分法查找,必須建立在排序的基礎之上
public static int binarySearch(int[] a,int flag){
// 開始下標0
int beginPos = 0;
// 結束下標
int endPos = a.length - 1;
while(beginPos <= endPos){
int midPos = (beginPos + endPos) / 2;
if(flag == a[midPos]){
return midPos;
} else if(flag > a[midPos]){
beginPos = midPos + 1;
} else if(flag < a[midPos]){
endPos = midPos - 1;
}
}
return -1;
}
}
冒泡
public static void sort(Object []arr){
boolean sorted=true;
int len= arr.length;
for(int i =0;i<len-1;i++){
sorted=true;
for(int j =0;j<len-i-1;j++){
if((Comparable)arr[j].compareTo(arr[j+1])<0){
Object temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
sorted=false;
}
}
}
if(sorted){break;}
}