对整型数组排序的静态方法代码如下:
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; } } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示
- ¥15 求三国群英传pl国战时间的修改方法
- ¥15 matlab代码代写,需写出详细代码,代价私
- ¥15 ROS系统搭建请教(跨境电商用途)
- ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。