Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

45
LINES

< > BotCompany Repo | #1029037 // intersectSortedIntArrays - recursive version!

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (115L/1K).

scope intersectSortedIntArrays.

// may return null when result is empty
static int[] intersectSortedIntArrays(int[] a, int[] b, IntBuffer buf default null) {
  int i = 0, j = 0, la = lIntArray(a), lb = lIntArray(b);
  
  // swap if a is longer than b
  if (la > lb) {
    int[] temp = a; a = b; b = temp;
    int temp2 = la; la = lb; lb = temp2;
  }
  
  // special case zero elements
  if (la == 0) null;
  
  // special case one element
  if (la == 1)
    ret Arrays.binarySearch(b, a[0]) >= 0 ? a : null;
    
  if (buf == null) buf = new IntBuffer; else buf.reset();
  recurse(a, b, buf, 0, la, 0, lb);
  ret buf.toArray();
}

svoid #recurse(int[] a, int[] b, IntBuffer buf, int aFrom, int aTo, int bFrom, int bTo) {
  if (aFrom >= aTo || bFrom >= bTo) ret; // nothing to do
  
  // start in the middle of a, search this element in b
  int i = (aFrom+aTo)/2;
  int x = a[i];
  int j = Arrays.binarySearch(b, bFrom, bTo, x);

  if (j >= 0) {
    // element found
    recurse(a, b, buf, aFrom, i, bFrom, j);
    buf.add(x);
    recurse(a, b, buf, i+1, aTo, j+1, bTo);
  } else {
    j = -j-1;
    recurse(a, b, buf, aFrom, i, bFrom, j);
    recurse(a, b, buf, i+1, aTo, j, bTo);
  }
}

end scope

Author comment

Began life as a copy of #1029031

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1029037
Snippet name: intersectSortedIntArrays - recursive version!
Eternal ID of this version: #1029037/4
Text MD5: 3307441caa1cbeba2c99a01f76cc1c6e
Transpilation MD5: ab84789ad0f0231870a426ed4657c22f
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-17 03:09:46
Source code size: 1242 bytes / 45 lines
Pitched / IR pitched: No / No
Views / Downloads: 145 / 222
Version history: 3 change(s)
Referenced in: [show references]