If you are a c# beginner or want to start learning the c# programming language, then this program will help you to understand the basics of c# programming. In this program, we are going to share the C# program to sort an array of 0, 1 and 2 with the output.
Copy the below c# program and execute it in your Microsoft Visual Studio IDE (Integrated Development Environment ). At the end of this program, I have shared the output program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using System; class FWM { static void sort012(int []a, int arr_size) { int lo = 0; int hi = arr_size - 1; int mid = 0,temp=0; while (mid <= hi) { switch (a[mid]) { case 0: { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; break; } case 1: mid++; break; case 2: { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; break; } } } } static void printArray(int []arr, int arr_size) { int i; for (i = 0; i < arr_size; i++) Console.Write(arr[i] + " "); Console.WriteLine(""); } public static void Main () { int []arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.Length; sort012(arr, arr_size); Console.Write("Array after seggregation "); printArray(arr, arr_size); } } |
array after segregation 0 0 0 0 0 1 1 1 1 1 2 2
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.