Matching elements in an array


/ Published in: Java
Save to your folder(s)

compare individual array elements with one another, without doing the same comparison twice (3vs2 then 2vs3). this reduces the number of iterations by roughly half. it's still O(n^2), an 1000 member array won't iterate a 1000X1000 times, it will be (1000X999)/2. efficient!!
an array of 0,1,2,3 will print out the following:
01,02,03,,12,13,2,3
ENJOY MY MATHS


Copy this code and paste it in your HTML
  1. public static void main(String[] args) {
  2. String[] arr = {"0","1","2","3"};
  3. int len = arr.length;
  4. for(int p= 0;p<len;p++){
  5. for(int i=len;i-->p+1;){
  6. System.out.print(arr[p]+arr[i]+" ");
  7. }
  8. }
  9. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.