对整型数组排序的静态方法代码如下:
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();
}
}
其中SortMethod是一个接口,请定义该接口,并定义2个类实现该接口,并分别在这两个实现类中使用直接插入排序和冒泡排序实现sort方法。
然后在main方法中输入一个长度为8的数组,分别用两个实现类的对象作为实际参数调用newsort方法进行排序。例如:
int[] ns = new int[8];
......
InsertSort is = new InsertSort();
SortedInts.newsort(ns, is);
程序输入输出如下:
9 3 5 2 1 7 23 8
1 2 3 5 7 8 9 23
1 2 3 5 7 8 9 23
(注意:最后有一行空行)
java接口类程序,定义一个接口并定义两个类实现该接口,然后在类中使用排序方法,然后在main中输入一个长度为8的数组,分别用两个实现类作为实参调用newsort进行排序
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 南七灵 2021-12-17 16:59关注
import java.util.*; public class Test { public static void main(String[] args){ int[] ns1 = new int[8]; int[] ns2 = new int[8]; Scanner sc = new Scanner(System.in); for(int i = 0;i < 8;i++){ ns1[i] = sc.nextInt(); ns2[i] = ns1[i]; } sc.close(); InsertSort is = new InsertSort(); SortedInts.newsort(ns1, is); BubbleSort bs = new BubbleSort(); SortedInts.newsort(ns2, bs); } } 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 interface SortMethod { public void sort(int[] number); }
public class InsertSort implements SortMethod{ @Override public void sort(int[] number) { for(int i=1; i<number.length; i++){ for(int j=i; j>0; j--){ if(number[j] < number[j-1]){ int temp = number[j-1]; number[j-1] = number[j]; number[j] = temp; } } } } }
public class BubbleSort implements SortMethod{ @Override public void sort(int[] number) { for(int i = 0;i < number.length - 1;i++){ for(int j = 0;j < number.length - 1 - i;j++){ if(number[j] > number[j+1]){ int temp = number[j]; number[j] = number[j+1]; number[j+1] = temp; } } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
- ¥20 腾讯企业邮箱邮件可以恢复么
- ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
- ¥15 错误 LNK2001 无法解析的外部符号
- ¥50 安装pyaudiokits失败
- ¥15 计组这些题应该咋做呀
- ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
- ¥15 让node服务器有自动加载文件的功能
- ¥15 jmeter脚本回放有的是对的有的是错的
- ¥15 r语言蛋白组学相关问题