如何测试Java中的快速排序算法

   2024-09-30 9460
核心提示:要测试Java中的快速排序算法,首先需要实现一个快速排序函数,然后创建一些测试用例来验证算法的正确性实现快速排序算法:public

要测试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测试框架运行上述测试用例。所有测试用例应通过,表明快速排序算法实现正确。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号