Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-08-26 11:01:12
forward
1378 people have browsed it

如何使用 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();
      }
   }
}
Copy after login

Output

0 0 0 0 1 1 1 1 2 2 2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template