Home >Java >Javagetting Started >What is the efficient way to merge ordered arrays in java
Let’s take a look at the original question first:
(Learning video sharing: java teaching video)
/** * ClassName: MergeSortArray <br/> * Function: 合并有序数组<br/> * [1, 2, 2, 5] * [3, 4, 7, 8, 9] * * */
Idea analysis :
Double pointers move the comparison from front to back, and then copy the remaining data to the merged array. In fact, this is also the core code of merge sort. Merge sort (split first and then merge) is divided and conquered. part of governance.
Implementation code:
public static int[] mergeSortArray(int[] a, int[] b){ int length1 = a.length, length2 = b.length; int[] merge = new int[length1 + length2]; int i = 0, j = 0, k = 0; while(i < length1 && j < length2){ if(a[i] <= b[j]){ merge[k++] = a[i++]; }else{ merge[k++] = b[j++]; } } while(i < length1){ merge[k++] = a[i++]; } while(j < length2){ merge[k++] = b[j++]; } return merge; } public static void main(String[] args) { int[] a = {1, 2, 2, 5}; int[] b = {3, 4, 7, 8, 9}; int[] merge = mergeSortArray(a, b); for(int i = 0; i < merge.length; i++){ System.out.println(merge[i]); } }
Running result:
1 2 2 3 4 5 7 8 9
Related recommendations: java introductory tutorial
The above is the detailed content of What is the efficient way to merge ordered arrays in java. For more information, please follow other related articles on the PHP Chinese website!