用c#写一个快速排序
时间: 2023-06-29 09:10:30 浏览: 41
以下是使用C#编写的快速排序算法:
```csharp
public static void QuickSort(int[] arr, int left, int right) {
if (left < right) {
int pivotIndex = Partition(arr, left, right);
QuickSort(arr, left, pivotIndex - 1);
QuickSort(arr, pivotIndex + 1, right);
}
}
public 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++;
Swap(arr, i, j);
}
}
Swap(arr, i + 1, right);
return i + 1;
}
public static void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
```
运行示例:
```csharp
int[] arr = { 3, 7, 2, 8, 1, 9, 4, 6, 5 };
QuickSort(arr, 0, arr.Length - 1);
foreach (int num in arr) {
Console.Write(num + " ");
}
// 输出:1 2 3 4 5 6 7 8 9
```