/**
* Created with Intellij IDEA
* ClassName:BinarySearch
* User:MaLe
* Description:给定一个有序整型数组, 实现二分查找
* @Date:2021/10/16
* @Time:15:51
* @author:395645313@qq.com
*/
public class BinarySearch {
public static int binarySearch(int[] arr,int n){
int i=0;
int j=arr.length-1;
while (i<=j) {
int mid=(i+j)/2;
if (n < arr[mid]) {
j=mid-1;
} else if (n > arr[mid]) {
i=mid+1;
} else if (n == arr[mid]) {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6,7,8,9};
int a=binarySearch(arr,9);
System.out.println(a);
}
}
二、冒泡排序
import java.util.Arrays;
/**
* Created with Intellij IDEA
* ClassName:Bubble
* User:MaLe
* Description:给定一个整型数组, 实现冒泡排序(升序排序)
* @Date:2021/10/16
* @Time:15:17
* @author:395645313@qq.com
*/
public class Bubble {
public static int[] bub(int[] arr){
int a=0;
for (int i = 0; i <arr.length-1 ; i++) {
boolean flag=false;
for (int j = 0; j <arr.length-1-i ; j++) {
if (arr[j]>arr[j+1]){
a=arr[j];
arr[j]=arr[j+1];
arr[j+1]=a;
flag=true;
}
}
if (flag=false){
return arr;
}
}
return arr;
}
public static void main(String[] args) {
int[] arr={1,9,5,8,4,78};
System.out.println("排序前:");
System.out.println(Arrays.toString(arr));
int[] c=bub(arr);
System.out.println("排序后:");
System.out.println(Arrays.toString(c));
}
}