以下是使用 C# 编写的快速排序算法:

using System;

class QuickSort {
    static void Main() {
        int[] arr = { 5, 2, 8, 3, 1, 6, 4, 7 };
        QuickSortAlgorithm(arr, 0, arr.Length - 1);
        for (int i = 0; i < arr.Length; i++) {
            Console.Write(arr[i] + " ");
        }
    }

    static void QuickSortAlgorithm(int[] arr, int left, int right) {
        if (left < right) {
            int pivotIndex = Partition(arr, left, right);
            QuickSortAlgorithm(arr, left, pivotIndex - 1);
            QuickSortAlgorithm(arr, pivotIndex + 1, right);
        }
    }

    static int Partition(int[] arr, int left, int right) {
        int pivot = arr[right];
        int i = left - 1;

        for (int j = left; j < right; j++) {
            if (arr[j] < pivot) {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        int temp1 = arr[i + 1];
        arr[i + 1] = arr[right];
        arr[right] = temp1;

        return i + 1;
    }
}

在主函数中,我们首先定义一个整型数组并初始化它。然后,我们调用 QuickSortAlgorithm 函数,并将数组、左端点和右端点作为参数传递给它。在 QuickSortAlgorithm 函数中,我们首先检查左端点是否小于右端点。如果是,则继续执行算法。我们计算出中心位置,然后递归地对左侧和右侧的子数组进行排序。在 Partition 函数中,我们选择数组的最后一个元素作为主元素,并将数组划分为两个部分。比主元素小的元素被放在左侧,比主元素大的元素被放在右侧。最后,我们将主元素放在数组的正确位置,然后返回该位置。

快速排序算法的优点:

  • 效率高:平均时间复杂度为 O(n log n),在最坏情况下时间复杂度为 O(n^2)。
  • 原地排序:不需要额外的存储空间。

快速排序算法的缺点:

  • 不稳定:对于相同值的元素,排序后顺序可能发生改变。
  • 递归深度:递归深度可能导致栈溢出。

总结:

快速排序算法是一种高效的排序算法,适用于大多数情况。但在一些情况下,例如数组中存在大量重复元素,或者数组已经接近有序时,快速排序算法的效率会下降。对于这些情况,可以考虑使用其他排序算法,例如归并排序或堆排序。

C# 快速排序算法实现详解及代码示例

原文地址: https://www.cveoy.top/t/topic/lKC9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录