定义一个存放在包com.inter下的接口Sort,接口中定义了排序方法sort()。编写该接口的实现类,实现选择排序ChoiceSort和冒泡排序BubbleSort,分别实现对一组整数的降序排列。再编写一个测试类TestSort,在测试类的主方法中通过Sort对象(接口回调)调用方法sort(),分别实现对一组整数的选择算法和冒泡算法的降序排列并输出排序结果。
时间: 2024-03-16 22:42:18 浏览: 32
请参考以下代码实现:
Sort.java
```java
package com.inter;
public interface Sort {
void sort(int[] arr);
}
```
ChoiceSort.java
```java
package com.inter;
public class ChoiceSort implements Sort {
@Override
public void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
if (maxIndex != i) {
int tmp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = tmp;
}
}
}
}
```
BubbleSort.java
```java
package com.inter;
public class BubbleSort implements Sort {
@Override
public void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
}
```
TestSort.java
```java
package com.inter;
public class TestSort {
public static void main(String[] args) {
int[] arr = {4, 2, 8, 5, 1, 6};
Sort choiceSort = new ChoiceSort();
choiceSort.sort(arr);
System.out.println("选择排序结果:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
Sort bubbleSort = new BubbleSort();
bubbleSort.sort(arr);
System.out.println("冒泡排序结果:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果:
```
选择排序结果:
8 6 5 4 2 1
冒泡排序结果:
8 6 5 4 2 1
```