|
发表于 2023-12-19 23:49:30
|
显示全部楼层
非常抱歉之前的修正仍然存在错误。我再次检查了代码,并发现了几处问题。以下是修复后的代码:
- // 定义SortMethod接口
- interface SortMethod {
- void sort(int[] numbers);
- }
- // 实现直接插入排序的类
- class InsertSort implements SortMethod {
- @Override
- public void sort(int[] numbers) {
- for (int i = 1; i < numbers.length; i++) {
- int key = numbers[i];
- int j = i - 1;
- while (j >= 0 && numbers[j] > key) {
- numbers[j + 1] = numbers[j];
- j--;
- }
- numbers[j + 1] = key;
- }
- }
- }
- // 实现冒泡排序的类
- class BubbleSort implements SortMethod {
- @Override
- public void sort(int[] numbers) {
- for (int i = 0; i < numbers.length - 1; i++) {
- for (int j = 0; j < numbers.length - 1 - i; j++) {
- if (numbers[j] > numbers[j + 1]) {
- int temp = numbers[j];
- numbers[j] = numbers[j + 1];
- numbers[j + 1] = temp;
- }
- }
- }
- }
- }
- // SortedInts类,包含newsort静态方法用于排序并输出结果
- class SortedInts {
- public static void newsort(int[] numbers, SortMethod s) {
- s.sort(numbers);
- for (int n : numbers) {
- System.out.printf("%d ", n);
- }
- System.out.println();
- }
- }
- // 主程序入口
- public class Main {
- public static void main(String[] args) {
- // 输入数组
- int[] ns = {9, 3, 5, 2, 1, 7, 23, 8};
- // 创建InsertSort对象并调用newsort方法进行排序
- InsertSort is = new InsertSort();
- SortedInts.newsort(ns, is);
- // 创建BubbleSort对象并调用newsort方法进行排序
- BubbleSort bs = new BubbleSort();
- SortedInts.newsort(ns, bs);
- }
- }
复制代码
在该修正后的代码中,我更正了以下几点错误:
1. 修改了`sort`方法的参数类型为`int[]`,以正确接收整型数组。
2. 在直接插入排序中,修正了`key`的赋值为`numbers`,并在内循环中使用`numbers[j]`来比较和替换元素。
3. 在冒泡排序中,修正了两两比较与交换元素的逻辑,使用`numbers[j + 1]`进行比较,并进行交换操作。
4. 在主程序入口中,修正了数组的定义方式为`int[] ns = {9, 3, 5, 2, 1, 7, 23, 8}`。
现在,你可以再次尝试运行该修正后的代码,应该可以正确编译和输出排序结果。如果还有任何问题,请随时告诉我。非常抱歉之前的错误造成的困扰,感谢你的理解。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|