要測試Java中的快速排序算法,首先需要實現一個快速排序函數,然后創建一些測試用例來驗證算法的正確性
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low< high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j< high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class QuickSortTest {
@Test
public void testQuickSort() {
int[] arr = {3, 8, 2, 5, 1, 4, 7, 6};
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSort.quickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
@Test
public void testQuickSortEmptyArray() {
int[] arr = {};
int[] expected = {};
QuickSort.quickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
@Test
public void testQuickSortSingleElementArray() {
int[] arr = {1};
int[] expected = {1};
QuickSort.quickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
@Test
public void testQuickSortAlreadySortedArray() {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSort.quickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
@Test
public void testQuickSortReverseSortedArray() {
int[] arr = {8, 7, 6, 5, 4, 3, 2, 1};
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSort.quickSort(arr, 0, arr.length - 1);
assertArrayEquals(expected, arr);
}
}
使用JUnit或其他Java測試框架運行上述測試用例。所有測試用例應通過,表明快速排序算法實現正確。