
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort 0s and 1s in an Array without Extra Space using Chash
Take two-pointers, low, high. We will use low pointers at the start, and the high pointer will point at the end of the given array.
If array [low] =0, then no swapping required
If array [low] = 1, then swapping is required. Decrement high pointer once.
Time complexity − O(N)
Example
using System; namespace ConsoleApplication{ public class Arrays{ public void SwapZerosOnes(int[] arr){ int low = 0; int high = arr.Length - 1; while (low < high){ if (arr[low] == 1){ Swap(arr, low, high); high--; } else{ low++; } } } private void Swap(int[] arr, int pos1, int pos2){ int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arr1 = { 0, 1, 1, 0, 1, 1 }; a.SwapZerosOnes(arr1); for (int i = 0; i < arr1.Length; i++){ Console.WriteLine(arr1[i]); } } } }
Output
0 0 1 1 1 1
Advertisements