java方法从键盘依次输入6本图书信息(以顺序表存放),要求按价格升序顺序输入,以折半查找算法
时间: 2024-02-17 14:04:08 浏览: 74
好的,以下是一个实现该功能的Java代码示例:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 创建一个长度为6的顺序表存放图书信息
Book[] books = new Book[6];
// 从键盘输入6本图书信息
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
System.out.println("请输入第" + (i + 1) + "本图书信息:");
System.out.print("书名:");
String name = scanner.nextLine();
System.out.print("价格:");
double price = scanner.nextDouble();
scanner.nextLine(); // 读取换行符
books[i] = new Book(name, price);
}
// 按价格升序顺序输入
sort(books);
// 使用折半查找算法查找价格最高的图书
int index = binarySearch(books, books[5].getPrice());
System.out.println("价格最高的图书信息为:");
System.out.println(books[index]);
}
// 冒泡排序实现按价格升序顺序排序
public static void sort(Book[] books) {
for (int i = 0; i < books.length - 1; i++) {
for (int j = 0; j < books.length - 1 - i; j++) {
if (books[j].getPrice() > books[j + 1].getPrice()) {
Book temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
// 折半查找算法实现查找价格为key的图书下标
public static int binarySearch(Book[] books, double key) {
int low = 0;
int high = books.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (books[mid].getPrice() == key) {
return mid;
} else if (books[mid].getPrice() > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // 未找到
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "书名:" + name + ",价格:" + price;
}
}
```
该程序会依次从键盘输入6本图书信息,然后按价格升序顺序排序,并使用折半查找算法查找价格最高的图书,最后输出该图书信息。
阅读全文