Home  >  Article  >  Backend Development  >  How to sort 0,1,2 in an array (Dutch flag) without extra space using C#?

How to sort 0,1,2 in an array (Dutch flag) without extra space using C#?

PHPz
PHPzforward
2023-08-26 11:01:121357browse

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

We need three-pointers, low, mid, and high. We will use low and mid pointers at the beginning and high pointer will point to the end of the given array.

If array [mid] =0, swap array [mid] with array [low]] and increment both pointers once.

If array [mid] = 1, no exchange is required. Increment the middle pointer once.

If array [mid] = 2, swap array [mid] with array [high] and decrement the high pointer once.

Time complexity - O(N)

Example

Real-time demonstration

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();
      }
   }
}

Output

0 0 0 0 1 1 1 1 2 2 2

The above is the detailed content of How to sort 0,1,2 in an array (Dutch flag) without extra space using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:SortedSet class in C#Next article:SortedSet class in C#