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+"位");
}
}
}