There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
Example 1:
nums1 = [1, 3] nums2 = [2]
The median is 2.0
Example 2: nums1 = [1, 2] nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Here is my solution:
//Find out the median of two sorted array
public class Median {
public static void main(String args[]){
int arr1[]={1,2,6};
int arr2[]={3,5,7};
int temp[]=new int[(arr1.length)+(arr2.length)];
int k=0,i=0,j=0,mid=0,k2=0;
while(i< arr1.length && j<arr2.length) {
if (arr1[i] < arr2[j]) {
temp[k] = arr1[i];
i++;
} else {
temp[k] = arr2[j];
j++;
}
k++;
}
while (i < arr1.length) {
temp[k++] = arr1[i++];
}
while (j < arr2.length) {
temp[k++] = arr2[j++];
}
int a= temp.length;
if(a%2==0){
k2=(temp.length)/2;
mid = (temp[k2]+temp[k2-1])/2;
}
else{
int k1=(int)(temp.length)/2;
mid=temp[k1];
}
System.out.println("The median of two sorted array is "+mid);
}
}
I want to know that what is the time complexity of my code? Is there any better way to solve this?
I know how to find out the time complexity if there is for loop. But if there is while loop then how could I find out the time complexity?
whileloops andforloops. If you understand how to do one (as distinct from just having some recipe that you use because you've been told that it works), you understand how to do the other. – David Richerby Nov 20 '18 at 12:06forloops always translate (more or less) to simple sums;whileloops can have arbitrarily nasty "index" domains. That said, thewhileloops here are badly-writtenforloops, so the strategies for analyzingforloops definitely apply. – Raphael Nov 20 '18 at 20:06whileloop is a little more interesting. A question that focuses on analyzing such a loop, removing all the "boring" stuff around it, may be able to stand on its own. – Raphael Nov 20 '18 at 20:08whileloops together; Knuth's method works well. – Raphael Nov 20 '18 at 20:09