题目:
编写程序,完成以下功能:
(1)输入5个整数到数组中;
(2)使用冒泡法对5个数按从小到大排序,输出排序后的数组;
(3)输入一个整数X,在数组中用二分法查找X,找到输出X在数组中的下标,找不到输出-1;
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));
}
}