【算法】快速排序

本文介绍快速排序的基本概念及其在C#中的实现。快速排序是一种高效的排序算法,通过递归方式将数组分为两部分并进行排序。文章提供了一个使用C#编写的快速排序示例,包括随机生成数组、排序过程的输出以及最终排序结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速排序(Quicksort)是对冒泡排序的一种改进。

快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

C#代码实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 快速排序
{
    class Program
    {
        public static void Main(string[] args)
        {
            //int[] num = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

            //随机生成10个数存放进数组,并打印出来:
            int[] num = new int[10];
            Random random = new Random();
            Console.WriteLine("原始待排序数组:");
            for (int i = 0; i < num.Length; i++)
            {
                num[i] = random.Next(1, 100);
                Console.Write(num[i] + "   ");
            }

            //打印空行,显示美观
            Console.WriteLine();

            //调用封装好的快速排序方法:
            QuickSorting quicksorting = new QuickSorting();
            quicksorting.QuickSort(num, 0, num.Length - 1);

            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 快速排序
{
    public class QuickSorting
    {

        int sortsum = 0;
        //一趟快速排序的算法:
        public int QuickPartition(int[] num, int low, int high)
        {
            int x = num[low];

            while (low < high)
            {
                while ((low < high) && (num[high] >= x)) --high;
                num[low] = num[high];
                while ((low < high) && (num[low ] <= x)) ++low;
                num[high] = num[low];
            }
            num[low] = x;
            sortsum++;
            
            Console.Write("\n" + "第" + sortsum + "趟的排序结果:");
            for (int i = 0; i < num.Length; i++)
            {
                Console.Write(num[i] + "   ");
            }
            Console.WriteLine();
            return low;
        }
        //完整的排序算法:
        public void QuickSort(int[] num, int low, int high)
        {
            if (low < high)
            {
                int temp = QuickPartition(num, low, high);
                QuickSort(num, low, temp - 1);
                QuickSort(num, temp + 1, high);
            }
        }
    }
}

控制台运行结果展示:

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值