I want to write a method that when supplied an array of ints will do the following. For each pair of array elements it will combine them and put them into a list of an inner class objects. Then it will compare each element in the array and check if it will fit between each pair values. (i.e. I have an array 0, 2, 4 it will make for example pair (0,4) and then it will check that value 2 is indeed between 0 and 4 and so for pair (4,0). When pair (0, 2) is evaluated it won’t find anything and therefore counter will increase (and so for pair (2, 0)). I have constructed the following code to evaluate number of values that indeed will fit in pairs and I hoped then to get the total number of pairs that match my need by extracting it from the total number of pairs. Now I want to optimize this query (in case I have very big arrays with thousands of members and very big or negative integers e.g. 1,000,000,000 or – 2,000,000,000). Please let me know how to do that. Mainly please focus on optimization issues thank you.
import java.util.*;
import java.util.Map;
import java.lang.*;
public class Prac1 {
public int count(int[] A){
int k = 0;
class PTemp{
int first = 0;
int second = 0;
public PTemp(int first, int second){
this.first = first;
this.second = second;
}
}
List<PTemp> r = new ArrayList<PTemp>();
int z = 0;
for (int i = 0; i < A.length; i++) {
for (int j = i+1; j < A.length; j++) {
r.add(new PTemp(A[i], A[j]));
r.add(new PTemp(A[j], A[i]));
z = z + 2;
System.out.println("["+A[i] +","+A[j]+"]");
System.out.println("["+A[j] +","+A[i]+"]");
}
}
Iterator<PTemp> ir = r.iterator();
while (ir.hasNext()){
PTemp p = ir.next();
label1:
for (int i = 0; i < A.length-1; i++){
if (((p.first < A[i]) && (A[i] < p.second)) || ((p.first > A[i]) && (A[i] > p.second))){
k = k + 1;
break label1;
}
}
}
System.out.println(z);
k = z - k;
return k;
}
public int c(int[] A) {
int z = (A.length - 1) * 2;
return z;
}
public static void main(String[] args){
int[] A = {0, 2, 2, 6, 5, 5};
Prac1 pr = new Prac1();
System.out.println(pr.count(A));
System.out.println(pr.c(A));
}
}
Without loss of generality, we can consider the array to be sorted. Assuming all numbers in the array are distinct, the pairs without elements in between are the pairs formed by neighbours. There are (array.length – 1) * 2 such pairs, i.e. you could simply do:
If the array may contain duplicates, you should specify how they are to be counted.