如何使用 C# 对数组(荷兰国旗)中的 0、1、2 进行排序,且不占用额外空间?
csharpserver side programmingprogramming更新于 2025/6/27 21:07:17
我们需要三个指针:low、mid、high。low 和 mid 指针分别指向数组的开头和结尾,high 指针指向数组的末尾。
如果数组 [mid] = 0,则将数组 [mid] 与数组 [low] 交换,并将两个指针都加 1。
如果数组 [mid] = 1,则无需交换。将 mid 指针加 1。
如果数组 [mid] = 2,则将数组 [mid] 与数组 [high] 交换,并将 high 指针减 1。
时间复杂度 - O(N)
示例
using System;
namespace ConsoleApplication{
public class Arrays{
private void Swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
public void DutchNationalFlag(int[] arr){
int low = 0;
int mid = 0;
int high = arr.Length - 1;
while (mid <= high){
if (arr[mid] == 0){
Swap(arr, low, mid);
low++;
mid++;
}
else if (arr[mid] == 2){
Swap(arr, high, mid);
high--;
}
else{
mid++;
}
}
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr = { 2, 1, 1, 0, 1, 2, 1, 2, 0, 0, 1 };
a.DutchNationalFlag(arr);
for (int i = 0; i < arr.Length; i++){
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}
}
输出
0 0 0 0 1 1 1 1 2 2 2

