如何使用 C# 在没有额外空间的情况下对数组(荷兰国旗)中的 0,1,2 进行排序?

我们需要投三分球,低、中、高。我们将在开始时使用低指针和中指针,高指针将指向给定数组的末尾。

如果数组 [mid] =0,则将数组 [mid] 与数组 [low] 交换,并将两个指针递增一次。

如果数组 [mid] = 1,则不需要交换。增加中间指针一次。

如果数组 [mid] = 2,那么我们将数组 [mid] 与数组 [high] 交换并递减一次高指针。

时间复杂度 - 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