Java实现二分查找算法等题
1.实现二分查找算法:有序的数组
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入你想安排的元素个数:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("输入有序的元素+空格不断输入:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("输入你想查询的数字key:");
int key = scanner.nextInt();
int indexNum = binarySearch(arr, key);
System.out.println("与key相等的元素下表为:" + indexNum);
}
static int binarySearch(int[] arr, int a) {
int low = 0;
int high = arr.length - 1;
int count = 1;
while (low <= high) {
System.out.println("第" + count + "次二分查找范围" + low + "---------------" + high);
int mid = (low + high) / 2;
if (arr[mid] == a) {
return mid;
} else if (arr[mid] > a) {
high = mid - 1 ;
} else {
low = mid + 1;
}
count++;
}
return -1;
}
}
2.求连续子数组的最大和?例如:{1,-3,5,9,-2,9}最小值:不能超过0x80000000
public class MaxArraysOnNum {
public static int maxArraysOnNum(int[] arr){
int maxSum = 0;
int numArr = 0;
for(int i = 0; i < arr.length; i++){
numArr = numArr + arr[i];
if(numArr < arr[i]){
numArr = arr[i];
maxSum = numArr;
}else if(numArr > maxSum){
maxSum = numArr;
}
}
return maxSum;
}
public static void main(String[] args) {
int[] arr = {1, -3, 5, 9, -2, 9};
System.out.println(maxArraysOnNum(arr));
}
}
3.交换两个数的几种方法
public class SwapNumber {
public static void swap1(int a1, int b1){
int temp;
temp = a1;
a1 = b1;
b1 = temp;
System.out.println("a1" + " = " + a1 + "; " + "b1" + " = " + b1 + '\n');
}
public static void swap2(int a2, int b2){
a2 = a2 + b2;
b2 = a2 - b2;
a2 = a2 - b2;
System.out.println("a2" + " = " + a2 + "; " + "b2" + " = " + b2 + '\n');
}
public static void swap3(int a3, int b3){
a3 = a3^b3;
b3 = a3^b3;
a3 = a3^b3;
System.out.println("a3" + " = " + a3 + "; " + "b3" + " = " + b3);
}
public static void main(String[] args) {
swap1(10, 20);
swap2(10, 20);
swap3(10, 20);
}
}
4.逆置数组:{1,2,3,4}===》{4,3,2,1}
import java.util.Scanner;
public class BackArrays {
public static void backArraysNum(int[] arr, int n){
for(n = arr.length - 1; n >= 0; n--){
System.out.print(arr[n] + " ");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入想要的数组长度:");
int n = scanner.nextInt();
int []arr = new int[n];
System.out.println("输入自己想输入的数(与长度相匹配):");
for(int i = 0; i < n; i++){
arr[i] = scanner.nextInt();
}
backArraysNum(arr, n);
}
}
2018-10.16/周二
by 922