温馨提示×

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

小樊
83
2024-09-09 18:34:45
栏目: 编程语言

要测试Java中的快速排序算法,首先需要实现一个快速排序函数,然后创建一些测试用例来验证算法的正确性

  1. 实现快速排序算法:
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;
    }
}
  1. 编写测试用例:
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);
    }
}
  1. 运行测试用例:

使用JUnit或其他Java测试框架运行上述测试用例。所有测试用例应通过,表明快速排序算法实现正确。

0