java - How to merge two sorted arrays into a sorted array? -


this asked of me in interview , solution provided:

public static int[] merge(int[] a, int[] b) {      int[] answer = new int[a.length + b.length];     int = 0, j = 0, k = 0;     while (i < a.length && j < b.length)     {         if (a[i] < b[j])         {             answer[k] = a[i];             i++;         }         else         {             answer[k] = b[j];             j++;         }         k++;     }      while (i < a.length)     {         answer[k] = a[i];         i++;         k++;     }      while (j < b.length)     {         answer[k] = b[j];         j++;         k++;     }      return answer; } 

is there more efficient way this?

edit: corrected length methods.

a minor improvement, after main loop, use system.arraycopy copy tail of either input array when end of other. won't change o(n) performance characteristics of solution, though.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -