CSharp 实现随机快速排序random quick sort 源代码
时间: 2023-10-18 12:13:18 浏览: 91
快速排序源码
好的,以下是 C# 实现的随机快速排序的源代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
int[] arr = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
QuickSort(arr, 0, arr.Length - 1);
Console.WriteLine(string.Join(",", arr));
}
static void QuickSort(int[] arr, int left, int right)
{
if (left < right)
{
int pivotIndex = RandomPartition(arr, left, right);
QuickSort(arr, left, pivotIndex - 1);
QuickSort(arr, pivotIndex + 1, right);
}
}
static int RandomPartition(int[] arr, int left, int right)
{
Random random = new Random();
int pivotIndex = random.Next(left, right + 1);
int pivotValue = arr[pivotIndex];
Swap(arr, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++)
{
if (arr[i] <= pivotValue)
{
Swap(arr, i, storeIndex);
storeIndex++;
}
}
Swap(arr, storeIndex, right);
return storeIndex;
}
static void Swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```
希望能对您有所帮助!接下来您还有什么问题需要我回答吗?
阅读全文