快速排序(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);
}
}
}
}
控制台运行结果展示: