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

1949idc 2年前 (2024-09-19) 阅读数 418 #编程语言

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

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业