sumit
BAN USER- 0of 0 votes
AnswersDo in place sorting of the given array such that all 0's moves to right and all 1's to left and their relative positioning remains same. Input array a =01001011101
- sumit in India
output : 00000111111| Report Duplicate | Flag | PURGE
Persistent Systems Software Engineer / Developer Arrays
//considering no. of 0 and 1s in array are same it will take o(n/2) time
int[] a = {0, 1, 1, 0, 0, 0, 0, 1, 1, 1};
int i = 0;
int j = a.length - 1;
int temp = 0;
do {
if (a[i] == 0 && a[j] == 1) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
if (a[i] == 1) {
i++;
}
if (a[j] == 0) {
j--;
}
} while (i < j);
// 0 will be returned if no equilibrium point else index of the equilibrium point
public static int findEquilPoint(int[] Arr) {
int sumLArr = 0;
int sumRArr = 0;
int eqPoint = 1;
if (Arr.length < 3) {
System.out.println("Cannot find equilibrium point...");
return 0;
}
for (int i = 0; i < Arr.length; i++) {
if (i < eqPoint) {
sumLArr += Arr[i];
} else if (i > eqPoint) {
sumRArr += Arr[i];
}
}
while (eqPoint <= Arr.length - 2) {
if (sumLArr == sumRArr) {
return eqPoint;
} else {
sumLArr += Arr[eqPoint];
sumRArr -= Arr[eqPoint + 1];
eqPoint = eqPoint + 1;
}
}
return 0;
}
The reason why string is immutable can be:
1. Security : Since java uses String for various purpose like class loading, so if it was mutable someone could have changed my class com.abc. to com.pqr at runtime.
2. Improving performance: Any frequent change in a string requires various things to be re-calculated again like hashcode, length, since its immutable it just caches its hashcode which makes it very fast as a hashmap key
3. Can be safely shared between threads.
4. In case of String pool one string object/literal is referenced by many reference variables , so if any one of them change the value others will be automatically gets affected.
//take sum of square of each element in both arrays and see if sum is equal or not
- sumit February 25, 2012