冒泡排序和二分法查找
1.冒泡排序
int[] arr = {78,89,67,98,90,56,88}; for(int i=0; i<arr.length-1; i++){ for(int j=0; j<arr.length-1-i; j++){ if(arr[j]>arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for(int a:arr){ System.out.print(a+" "); }
运行结果:
2.二分法查找
/** * 一个数组,输入一个数字,查找该数字在数组中的下标。 如果找不到,返回-1 */ int[] arr = {0,1,2,3,4,5,6,7,8,9}; Scanner in = new Scanner(System.in); System.out.print("请输入一个数字:"); int num = in.nextInt(); /** * 二分法查找 */ int start = 0; // 默认起始坐标 int end = arr.length-1; // 默认结尾坐标 int index = -1; // 找不到默认index为-1 while(start<=end){ int middle = (start+end)/2; // 计算中间下标 if(num == arr[middle]){ index = middle; break; } if(num > arr[middle]){ start = middle + 1; } if(num < arr[middle]){ end = middle - 1; } } System.out.println(index); in.close();
运行结果: