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).

1  
scope intersectSortedIntArrays.
2  
3  
// may return null when result is empty
4  
static int[] intersectSortedIntArrays(int[] a, int[] b, IntBuffer buf default null) {
5  
  int i = 0, j = 0, la = lIntArray(a), lb = lIntArray(b);
6  
  
7  
  // swap if a is longer than b
8  
  if (la > lb) {
9  
    int[] temp = a; a = b; b = temp;
10  
    int temp2 = la; la = lb; lb = temp2;
11  
  }
12  
  
13  
  // special case zero elements
14  
  if (la == 0) null;
15  
  
16  
  // special case one element
17  
  if (la == 1)
18  
    ret Arrays.binarySearch(b, a[0]) >= 0 ? a : null;
19  
    
20  
  if (buf == null) buf = new IntBuffer; else buf.reset();
21  
  recurse(a, b, buf, 0, la, 0, lb);
22  
  ret buf.toArray();
23  
}
24  
25  
svoid #recurse(int[] a, int[] b, IntBuffer buf, int aFrom, int aTo, int bFrom, int bTo) {
26  
  if (aFrom >= aTo || bFrom >= bTo) ret; // nothing to do
27  
  
28  
  // start in the middle of a, search this element in b
29  
  int i = (aFrom+aTo)/2;
30  
  int x = a[i];
31  
  int j = Arrays.binarySearch(b, bFrom, bTo, x);
32  
33  
  if (j >= 0) {
34  
    // element found
35  
    recurse(a, b, buf, aFrom, i, bFrom, j);
36  
    buf.add(x);
37  
    recurse(a, b, buf, i+1, aTo, j+1, bTo);
38  
  } else {
39  
    j = -j-1;
40  
    recurse(a, b, buf, aFrom, i, bFrom, j);
41  
    recurse(a, b, buf, i+1, aTo, j, bTo);
42  
  }
43  
}
44  
45  
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: 150 / 228
Version history: 3 change(s)
Referenced in: [show references]