kth element in 2 sorted array

public int findKth(int[] arr1, int[] arr2, int k){ //check simple situation int n1 = arr1.length; int n2 = arr2.length; /* if (k > n1+n2 || k < 1) throw new Exception("invalid k");*/ if(n1 == 0 || n2 == 0) { return (n1 == 0)?arr2[k-1]:arr1[k-1]; } if (arr1[0] >= arr2[n2-1] || arr2[0] >= arr1[n1-1]){ return (arr1[0] >= arr2[n2-1])?arr2[k-1]:arr1[k-1]; } if(k == 1){ return (arr1[0] <= arr2[0])?arr1[0]:arr2[0]; } //regular situation int newk = (k-1)/2; if(arr1[newk] == arr2[newk]) return arr1[newk]; else if(arr1[newk] < arr2[newk]){ int[] newarr1 = Arrays.copyOfRange(arr1, newk, n1); int[] newarr2 = Arrays.copyOfRange(arr2, 0, newk+1); return findKth(newarr1, newarr2, k-newk); } else { int[] newarr1 = Arrays.copyOfRange(arr1, 0, newk+1); int[] newarr2 = Arrays.copyOfRange(arr2, newk, n2); return findKth(newarr1, newarr2, k-newk); } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.