1.二分查找
public class test {
public static void main(String[] args) {
// 定义数组
int[] arr ={81,51,88,15,59,20,1,50,66,77,4};
// 对数组进行升序排序
Arrays.sort(arr);
// 打印数组
System.out.println(Arrays.toString(arr));
// 打印查找结果
System.out.println(binarySearch(arr,59));
}
public static int binarySearch(int[]arr,int value){
int low = 0;
int high = arr.length-1;
// 循环直到不能再分
while (low<=high){
int mid = (low+high)/2;
if (value == arr[mid]){
// 返回匹配值的下标
return mid;
}
if (value < arr[mid]){
high = mid-1;
}
if (value > arr[mid]){
low = mid+1;
}
}
// 如果没有查找到值,则返回404
return 404;
}
}
2.冒泡排序
public class demo_sort {
public static void main(String[] args) {
//冒泡排序算法
int[] numbers=new int[]{1,5,8,2,3,9,4};
//需进行length-1次冒泡
for(int i=0;i<numbers.length-1;i++)
{
for(int j=0;j<numbers.length-1-i;j++)
{
if(numbers[j]>numbers[j+1])
{
int temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
}
}
}
System.out.println("从小到大排序后的结果是:");
for(int i=0;i<numbers.length;i++)
System.out.print(numbers[i]+" ");
}