Skip to content

Instantly share code, notes, and snippets.

@rozer007
Last active October 21, 2021 10:35
Show Gist options
  • Save rozer007/e4e0c41998efac0fb695b6dbea102b6b to your computer and use it in GitHub Desktop.
Save rozer007/e4e0c41998efac0fb695b6dbea102b6b to your computer and use it in GitHub Desktop.
pepcoding.com 19/10/21 sort012
#include <iostream>
#include <vector>
using namespace std;
void input(vector<int> &arr)
{
for (int i = 0; i < arr.size(); i++)
{
cin >> arr[i];
}
}
void print(vector<int> &arr)
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << endl;
}
cout << endl;
}
// used for swapping ith and jth elements of array
void swap(vector<int> &arr, int i, int j)
{
cout << ("Swapping index " + to_string(i) + " and index " + to_string(j)) << endl;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void sort012(vector<int> &arr)
{
int pt1=0,pt2=arr.size()-1;
int itr=0;
while(itr<=pt2)
{
if(arr[itr]==0)
{
swap(arr,itr++,pt1++);
}
else if(arr[itr]==2)
{
swap(arr,itr,pt2--);
}
else
itr++;
}
}
int main()
{
int n;
cin >> n;
vector<int> A(n, 0);
input(A);
sort012(A);
print(A);
return 0;
}
def printlist(arr):
for i in arr:
print(i)
# used for swapping ith and jth elements of array
def swap(arr, i, j):
print("Swapping index" , i , "and index" ,j);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
def sort012(arr):
pt1=0;pt2=len(arr)-1;itr=0;
while itr<=pt2:
if(arr[itr]==0):
swap(arr,itr,pt1);
itr+=1;
pt1+=1;
elif(arr[itr]==2):
swap(arr,itr,pt2);
pt2-=1;
else:
itr+=1;
n = int(input());
A= [];
for i in range(0, n):
val = int(input());
A.append(val) ;
sort012(A);
printlist(A);
#include <iostream>
#include <vector>
using namespace std;
void input(vector<int> &arr)
{
for (int i = 0; i < arr.size(); i++)
{
cin >> arr[i];
}
}
void print(vector<int> &arr)
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << endl;
}
cout << endl;
}
// used for swapping ith and jth elements of array
void swap(vector<int> &arr, int i, int j)
{
cout << ("Swapping index " + to_string(i) + " and index " + to_string(j)) << endl;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void sort012(vector<int> &arr)
{
//write your code here
}
int main()
{
int n;
cin >> n;
vector<int> A(n, 0);
input(A);
sort012(A);
print(A);
return 0;
}
def printlist(arr):
for i in arr:
print(i)
# used for swapping ith and jth elements of array
def swap(arr, i, j):
print("Swapping index" , i , "and index" ,j);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
def sort012(arr):
#write your code here
n = int(input());
A= [];
for i in range(0, n):
val = int(input());
A.append(val) ;
sort012(A);
printlist(A);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment