I know that addition is commutative therefore I want to perform a storing operation with shorthand operation =
at line 46 but the answer differs only when I put the parenthesis, also when when I don't put parenthesis I get wrong answer.
The line is in the merge function.
CODE:
public class ProblemA {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer> (Arrays.asList(1, 3, 2, 3, 1));
int n = arr.size();
//calling mergesort
int total = countPair(arr, n);
System.out.println(total);
}
public static int countPair(ArrayList<Integer> arr, int n) {
int total = mergeSort(arr, 0, n - 1);
return total;
}
public static int mergeSort(ArrayList<Integer> arr, int low, int high) {
//termination condition
if (low >= high) return 0;
//firstly we'll disassociate the elements of array on elementary level
int mid = (low high) / 2;
//we'll store our count value inside the counter variable
int inv = mergeSort(arr, low, mid);
inv = mergeSort(arr, mid 1, high);
inv = merge(arr, low, mid, high);
return inv;
}
public static int merge(ArrayList<Integer> arr, int low, int mid, int high) {
//AIM: make a double loop and traverse through the elements and increase the right side pointer
//whenever condition (arr[i]>2*arr[j] is satisfied)
//int i = 0;
int total = 0;
int j = mid 1;
for (int i = low; i<= mid; i ) {
//looping till we run out the right hand side or condition is not satisfied
while (j<= high && arr.get(i) > 2 * arr.get(j)) {
j ;
} **
* total = (j - (mid 1)); ** * //parenthesis error here
}
//Now we can move to merging part
ArrayList<Integer> temp = new ArrayList<Integer> ();
int left = low, right = mid 1;
while (left<= mid && right<= high) {
if (arr.get(left)<= arr.get(right)) {
temp.add(arr.get(left ));
} else {
temp.add(arr.get(right ));
}
}
//for the last right or left remaining element
while (left<= mid) {
temp.add(arr.get(left ));
}
while (right<= high) {
temp.add(arr.get(right ));
}
//now we can copy the remaining elements from temp list to arr
for (int i = low, k = 0; i<= high; i ) {
arr.set(i, temp.get(k ));
}
return total;
}
}
OUTPUT(with parenthesis) "total = (j-(mid 1))":
2
OUTPUT(without parenthesis) "total = j-mid 1":
16
CodePudding user response:
This is happening because if you use parenthesis, java will decide which expression you want to evaluate first. If you don't use parenthesis then everything goes executed from left to right. Example:
int total=1;
int total1=1;
int total2=1;
total =total1-total2 1;
System.out.println(total);
Output : 2
The reason is here, expression got evaluated as total=total total1-total2 1; i.e. total=1 1-1 1=2;
For parenthesis based expression, it gets evaluated first & then others:-
int total=1;
int total1=1;
int total2=1;
total =(total1-(total2 1));
System.out.println(total);
Output : 0 , evaluation will happen like below :-
total=total (1-(1 1));
total=1 (1-(2));
total=1 (-1);
total=0;
Reference : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html