冒泡排序代码:
public static void Bsort(int[] array) {
// TODO Auto-generated method stub
boolean flag=true;
int count=0;
for(int i=0;(i<array.length-1)&&flag;i++,count++){
flag=false;
for(int j=0;j<array.length-1-i;j++){
if(array[j]>array[j+1]){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
flag=true;
}
}
}
System.out.println("排序次数:"+count);
}
选择排序代码:
public static void Select(int[] arr) {
// TODO Auto-generated method stub
for(int x=0;x<arr.length-1;x++){
for(int y=x+1;y<arr.length;y++){
if(arr[x]>arr[y]){
int temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
}
}
}
二分法查找:
public static int binarySearch(int[] arr, int value) {
// TODO Auto-generated method stub
int min =0;
int max=arr.length-1;
int mid=(min+max)/2;
while(arr[mid]!=value){
if(arr[mid]>value){
max=mid-1;
}
if(arr[mid]<value){
min=mid+1;
}
mid=(min+max)/2;
if(min>max){
return -1;
}
}
return mid;
}