題目:
編寫程序,完成如下功能:
(1)輸入5個整數到數組中;
(2)使用冒泡法對5個數按從小到大排序,輸出排序後的數組;
(3)輸入一個整數X,在數組中用二分法查找X,找到輸出X在數組中的下標,找不到輸出-1;java
Java實現:數組
package com.company; import java.util.Scanner; class BinarySearch{ public int BSearch(int []arr , int search){ //冒泡排序 int count = 0; while(count < arr.length){ for(int i = 0 ; i < arr.length - 1 - count ; i ++){ int temp = 0; if(arr[i] > arr[i+1]){ temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } count ++; } //打印排序完的數組 System.out.print("排序後的數組爲:"); for(int i = 0 ; i < arr.length ; i ++){ System.out.print(arr[i] + " "); if(i == arr.length - 1){ System.out.println(); } } //二分查找 int top = 0; int rear = arr.length - 1; int mid = (top+rear)/2; if(search > arr[arr.length-1] || search < arr[0]){ return -1; } while(top <= rear){ mid = (top + rear) / 2; if(arr[mid] > search){ rear = mid - 1; }else if(arr[mid] < search){ top = mid + 1; }else{ return mid; } } return -1; } } public class Test4 { public static void main(String[] args) { int []array = new int[5]; //數組賦值 System.out.println("請輸入5個整數:"); Scanner input = new Scanner(System.in); for(int i = 0 ; i < 5 ; i ++){ array[i] = input.nextInt(); } BinarySearch bs = new BinarySearch(); System.out.println("請輸入要查找的數字:"); int search = input.nextInt(); System.out.println("你要查找的數字的下標是:"+bs.BSearch(array,search)); } }