- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathSort012.java
105 lines (82 loc) · 2.8 KB
/
Sort012.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Sort 0 1 2
// You are given an integer array/list(ARR)of size N.It contains only 0 s,1 s and 2 s.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.
// Note:
// You need to change in the given array/list itself.Hence,no need to return or print anything.
// Input format:
// The first line contains an Integer't'which denotes the number of test cases or queries to be run.Then the test cases follow.
// First line of each test case or query contains an integer'N'representing the size of the array/list.
// Second line contains'N'single space separated integers(all 0 s,1 s and 2 s)representing the elements in the array/list.
// Output Format:
// For each test case,print the sorted array/list elements in a row separated by a single space.
// Output for every test case will be printed in a separate line.
// Constraints:
// 1<=t<=10^2
// 0<=N<=10^5
// Time Limit:1 sec
// Sample Input 1:
// 1
// 7
// 0 1 2 0 2 0 1
// Sample Output 1:
// 0 0 0 1 1 2 2
// Sample Input 2:
// 2
// 5
// 2 2 0 1 1
// 7
// 0 1 2 0 1 2 0
// Sample Output 2:
// 0 1 1 2 2
// 0 0 0 1 1 2 2
packageArray;
importjava.util.Scanner;
publicclassSort012 {
publicstaticint [] takeInput() {
Scannersc = newScanner(System.in);
System.out.println("Enter the length of the array: ");
intn = sc.nextInt();
int [] arr = newint[n];
for (inti = 0; i < n; i++) {
System.out.println("Enter the element at " + i + " th index.");
arr[i] = sc.nextInt();
}
returnarr;
}
publicstaticvoidswap(int [] arr, inti, intj) {
// i = number to be swapped.
// j = number with which it is swapped.
inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
publicstaticint [] sort012threePointerApproach(int [] arr) {
inti = 0;
intj = 0;
intk = arr.length - 1;
while (i <= k) {
if (arr[i] == 1) {
i++;
} elseif (arr[i] == 0) {
swap(arr, i, j);
i++;
j++;
} else {
swap(arr, i, k);
k--;
}
}
returnarr;
}
publicstaticvoidprintArray(int [] arr) {
intn = arr.length;
for (inti = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
publicstaticvoidmain(String[] args) {
int [] arr = takeInput();
int [] finalArray = sort012threePointerApproach(arr);
printArray(finalArray);
}
}