非常抱歉之前的代码仍然存在错误。以下是修正后的代码: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; } } } }}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 is = new InsertSort(); SortedInts.newsort(ns, is); BubbleSort bs = new BubbleSort(); SortedInts.newsort(ns, bs); }}
再次感谢你的耐心,并对之前的错误表示歉意。这次提供的代码已经修正,应该能够正确运行并通过所有的测试。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |