用 java语言以测试驱动开发实现冒泡排序
时间: 2023-12-31 11:53:32 浏览: 38
以下是用 Java 语言实现冒泡排序的测试驱动开发示例:
```java
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class BubbleSortTest {
@Test
public void testBubbleSort() {
int[] arr = { 5, 1, 4, 2, 8 };
BubbleSort.bubbleSort(arr);
int[] expected = { 1, 2, 4, 5, 8 };
assertArrayEquals(expected, arr);
}
}
class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
上述代码中,我们先编写了一个测试用例 `testBubbleSort()`,该测试用例调用 `BubbleSort.bubbleSort()` 方法对一个无序数组进行排序,然后检查排序后的数组是否与预期的有序数组相同。接着,我们实现了 `BubbleSort` 类,该类包含了 `bubbleSort()` 方法,该方法实现了冒泡排序的算法。最后,我们运行测试用例,如果测试通过,则说明我们的冒泡排序实现是正确的。
这就是使用 Java 语言以测试驱动开发实现冒泡排序的示例。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)