Skip to content

Sort 0 1 2 #551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
  • Loading branch information
Sonu589 authored Oct 3, 2021
commit 31857aeea47ae53e62c7bcb4f90fc0a67f77bed6
26 changes: 26 additions & 0 deletions Sort 0 1 2
Original file line number Diff line number Diff line change
@@ -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++;
}
}
}