import java.util.Scanner;
public class ArrayDemo {
public static void main(String []args) {
//-------------------------------------------------------
//线性查找
int [] num ={10,20,30,40,50};
Scanner input1 = new Scanner(System.in);
System.out.println("请输入要查找的数(10,20,30,40,50):");
int inp = input1.nextInt();
input1.close();
for(int i = 0;i<num.length;i++) {
if (inp == num[i]) {
System.out.println("所查数下标为:"+i);
}else {
if(i==num.length-1 ) {
System.out.println("-1");
}
}
}
//-------------------------------------------------------
//查找数组最大值,最小值
int[] maxMin = new int[] {20,60,80,70,30,10,50};
System.out.println("数组为(20,60,80,70,30,10,50),求最大值和最小值:");
//方法一(冒泡排序):
int temp=0;
for(int i = 0;i<maxMin.length-1;i++) {
if(maxMin[i]>maxMin[i+1]) {
temp = maxMin[i+1];
maxMin[i+1] = maxMin[i];
maxMin[i] = temp;
}
}
System.out.println("最大值为:"+maxMin[6]);
for(int i = 0;i<maxMin.length-1;i++) {
if(maxMin[i]<maxMin[i+1]) {
temp = maxMin[i+1];
maxMin[i+1] = maxMin[i];
maxMin[i] = temp;
}
}
//方法二:
int max = maxMin[0];
for(int i = 1;i<maxMin.length-1;i++) {
if(maxMin[i]>max) {
max = maxMin[i];
}
}
System.out.println("最大值为:"+max);
int min = maxMin[0];
for(int i = 1;i<maxMin.length-1;i++) {
if(maxMin[i]<min) {
min = maxMin[i];
}
}
System.out.println("最小值为:"+min);
//--------------------------------------------------------
//二分查找
int[] BinarySearch = new int[] {10,20,30,40,70,80,90,100};
Scanner input2 = new Scanner(System.in);
System.out.println("请输入要查找的数(10,20,30,40,70,80,90,100):");
input2.close();
int start;
int end;
int middle;
int index = -1;//保存找到书所在下标
start = 0;//保存起始下标
end = BinarySearch.length-1;//保存终点下标
while(start <=end) {
middle = (start+end)/2;//找到中间元素 对应的值
if(num2 == BinarySearch[middle]) {
index = middle+1;
break;
}
if(num2 > BinarySearch[middle]) {//如果是大于中间的数
start = middle+1;//起始下标改为中间数的下一个数
}
if(num2 < BinarySearch[middle]){
end = middle-1;//终点下标改为中间数的上一个数
}
}
if(index == -1){
System.out.println("没查到");
}
else{
System.out.println("查到了,位置在第"+index+"位");
}
}
}