步驟 1:撰寫測試案例
在撰寫測試案例之前,我們需要確定 binarySort 方法的預期行為。根據描述,binarySort 方法應該能夠將輸入的整數陣列由小到大排序並返回。
測試案例設計
測試空陣列:
輸入:[]
預期輸出:[]
測試單一元素陣列:
輸入:[5]
預期輸出:[5]
測試已排序陣列:
輸入:[1, 2, 3, 4, 5]
預期輸出:[1, 2, 3, 4, 5]
測試逆序陣列:
輸入:[5, 4, 3, 2, 1]
預期輸出:[1, 2, 3, 4, 5]
測試包含重複元素的陣列:
輸入:[4, 2, 5, 2, 3]
預期輸出:[2, 2, 3, 4, 5]
測試包含負數的陣列:
輸入:[3, -1, 2, -5, 0]
預期輸出:[-5, -1, 0, 2, 3]
步驟 2:撰寫測試代碼
以下是使用 Java 的測試案例設計:
java
複製程式碼
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MySortTest {
@Test
void testEmptyArray() {
MySort sorter = new MySort();
int[] input = {};
int[] expected = {};
assertArrayEquals(expected, sorter.binarySort(input));
}
@Test
void testSingleElementArray() {
MySort sorter = new MySort();
int[] input = {5};
int[] expected = {5};
assertArrayEquals(expected, sorter.binarySort(input));
}
@Test
void testSortedArray() {
MySort sorter = new MySort();
int[] input = {1, 2, 3, 4, 5};
int[] expected = {1, 2, 3, 4, 5};
assertArrayEquals(expected, sorter.binarySort(input));
}
@Test
void testReverseArray() {
MySort sorter = new MySort();
int[] input = {5, 4, 3, 2, 1};
int[] expected = {1, 2, 3, 4, 5};
assertArrayEquals(expected, sorter.binarySort(input));
}
@Test
void testArrayWithDuplicates() {
MySort sorter = new MySort();
int[] input = {4, 2, 5, 2, 3};
int[] expected = {2, 2, 3, 4, 5};
assertArrayEquals(expected, sorter.binarySort(input));
}
@Test
void testArrayWithNegativeNumbers() {
MySort sorter = new MySort();
int[] input = {3, -1, 2, -5, 0};
int[] expected = {-5, -1, 0, 2, 3};
assertArrayEquals(expected, sorter.binarySort(input));
}
}
步驟 3:實現 binarySort 方法
接下來,我們需要實現 binarySort 方法,確保測試案例能夠通過。
java
複製程式碼
public class MySort {
public int[] binarySort(int[] data) {
if (data == null || data.length == 0) {
return data;
}
quickSort(data, 0, data.length - 1);
return data;
}
private void quickSort(int[] data, int low, int high) {
if (low < high) {
int pi = partition(data, low, high);
quickSort(data, low, pi - 1);
quickSort(data, pi + 1, high);
}
}
private int partition(int[] data, int low, int high) {
int pivot = data[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (data[j] < pivot) {
i++;
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
int temp = data[i + 1];
data[i + 1] = data[high];
data[high] = temp;
return i + 1;
}
}
總結
上述步驟和代碼展示了如何依據 TDD 的概念設計測試案例並實現排序方法 binarySort。透過這些測試案例,我們可以確保 binarySort 方法能夠正確地將輸入的整數陣列由小到大排序。