溫馨提示×

如何測試Java中的快速排序算法

小樊
83
2024-09-09 18:34:45
欄目: 編程語言

要測試Java中的快速排序算法,首先需要實現(xiàn)一個快速排序函數(shù),然后創(chuàng)建一些測試用例來驗證算法的正確性

  1. 實現(xiàn)快速排序算法:
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. 運(yùn)行測試用例:

使用JUnit或其他Java測試框架運(yùn)行上述測試用例。所有測試用例應(yīng)通過,表明快速排序算法實現(xiàn)正確。

0