From 31857aeea47ae53e62c7bcb4f90fc0a67f77bed6 Mon Sep 17 00:00:00 2001 From: Sonu589 <78155991+Sonu589@users.noreply.github.com> Date: Sun, 3 Oct 2021 23:28:48 +0530 Subject: [PATCH] Sort 0 1 2 You are given an integer array/list(ARR) of size N. It contains only 0s, 1s and 2s. Write a solution to sort this array/list in a 'single scan'. 'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once. --- Sort 0 1 2 | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Sort 0 1 2 diff --git a/Sort 0 1 2 b/Sort 0 1 2 new file mode 100644 index 0000000..61246df --- /dev/null +++ b/Sort 0 1 2 @@ -0,0 +1,26 @@ +public class Solution { + + public static void sort012(int[] arr){ + int nZ=0,nT=arr.length-1; + int tempforTwo=0; + int tempforZero=0; + int i=0; + while(i<=nT){ + if(arr[i]==0){ + tempforZero=arr[nZ]; + arr[nZ]=arr[i]; + arr[i]=tempforZero; + i++; + nZ++; + } + else if(arr[i]==2){ + tempforTwo=arr[nT]; + arr[nT]=arr[i]; + arr[i]=tempforTwo; + nT--; + } + else + i++; + } + } +}