fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void swap(int *a, int i, int j){
  5. int temp = a[i];
  6. a[i] = a[j];
  7. a[j] = temp;
  8. }
  9.  
  10. void sort012(int *a, int n)
  11. {
  12. int i = 0;
  13. int j = n-1;
  14.  
  15. // first loop sorts the array with 0 at front and {1, 2} at end
  16. while (i <j) {
  17. while (a[i] ==0 && i<j) {
  18. i++;
  19. }
  20. while ((a[j] == 1 && i<j) || (a[j] == 2 && i<j)) {
  21. j--;
  22. }
  23. if(i<j)
  24. {
  25. int temp=a[i];
  26. a[i]=a[j];
  27. a[j]=temp;
  28. i++;
  29. j--;
  30. }
  31. }
  32. for(int i=0;i<n;i++)
  33. cout<<a[i]<<" ";
  34. cout<<endl;
  35. cout<<endl;
  36. cout<<"i"<<i<<endl;
  37. cout<<"j"<<j<<endl;
  38.  
  39. // This loop sorts array of 1 & 2
  40.  
  41. if(i==j)
  42. i+=1;
  43. else if(i<j)
  44. i=j;
  45. j = n-1;
  46. cout<<endl;
  47. cout<<"i"<<i<<endl;
  48. cout<<"j"<<j<<endl;
  49. while (i <j) {
  50. while (a[i] ==1 && i<j) {
  51. i++;
  52. }
  53. while (a[j] == 2 && i<j) {
  54. j--;
  55. }
  56. if(i<j)
  57. {
  58. int temp=a[i];
  59. a[i]=a[j];
  60. a[j]=temp;
  61. i++;
  62. j--;
  63. }
  64. }
  65. for(int i=0;i<n;i++)
  66. cout<<a[i]<<" ";
  67. cout<<endl;
  68. }
  69.  
  70.  
  71.  
  72. int main()
  73. {
  74. //code
  75. int t; //test cases
  76. cin>>t;
  77. while(t--)
  78. {
  79. int n;
  80. cin>>n;
  81. int arr[n];
  82. for(int i=0;i<n;i++)
  83. cin>>arr[i];
  84. sort012(arr,n);
  85. }
  86. return 0;
  87. }
Success #stdin #stdout 0s 4368KB
stdin
3
85
0 2 2 1 0 0 2 0 1 1 1 0 0 2 0 1 2 1 2 0 2 2 0 0 1 2 1 2 2 1 0 2 1 2 1 0 0 1 0 2 0 2 0 1 0 1 2 0 0 2 1 2 2 2 1 0 2 2 0 2 0 0 1 2 1 0 0 2 2 1 2 0 1 2 2 1 2 2 1 2 1 1 2 1 0
3
0 1 0
8
0 0 1 0 0 0 1 2
stdout
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 1 1 2 1 2 1 2 1 1 2 2 2 2 2 1 1 1 2 2 1 2 1 2 2 2 1 2 2 2 1 2 1 1 1 2 1 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 1 1 2 1 2 

i27
j27

i28
j84
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 
0 0 1 

i2
j1

i2
j2
0 0 1 
0 0 0 0 0 1 1 2 

i4
j4

i5
j7
0 0 0 0 0 1 1 2