首頁  >  文章  >  後端開發  >  如何使用 C# 在沒有額外空間的情況下對數組(荷蘭國旗)中的 0,1,2 進行排序?

如何使用 C# 在沒有額外空間的情況下對數組(荷蘭國旗)中的 0,1,2 進行排序?

PHPz
PHPz轉載
2023-08-26 11:01:121315瀏覽

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

我們需要三分球,低位、中位、高位。我們將在開頭使用 low 和 mid 指針,而 high 指針將指向給定數組的末尾。

如果 array [mid] =0,則將 array [mid] 與 array [low] 交換] 並將兩個指標遞增一次。

如果 array [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

以上是如何使用 C# 在沒有額外空間的情況下對數組(荷蘭國旗)中的 0,1,2 進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除