Monday, October 13, 2014

#codingexercise
Median of two sorted arrays

int GetMedian(List<int> list1, List<int> list2)
{
  if (list1 == null || list1.Length <= 0) throw new Exception();
  if (list2== null || list2.Length <= 0) throw new Exception();
  int first = 0; // index for first
  int second = 0; // index for second;
  var merged = new List<int>();

 while (first <list1.Length && second < list2.length)
     if (list1[first] < list2[second])
     {
       merged.Add(list1[first]);
       first++;
      }
     else
       {
        merged.Add(list2[second])
        second++;
       }

  while (first<list1.Length){
        merged.Add(list1[first]);
        first++;
   }

   while (second < list2.Length) {
        merged.Add(list2[second]);
        second++;
   }
   
 int mid = (first + second) / 2;
 if  (mid %2 == 0)
  {
     if (mid -1 > 0)  return (merged[mid-1] + merged[mid]) / 2;
  }
 return merged[mid];
}

No comments:

Post a Comment