Home > Java > Javagetting Started > body text

What is the efficient way to merge ordered arrays in java

王林
Release: 2020-12-14 16:00:49
forward
2128 people have browsed it

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]
 *
 *
 */
Copy after login

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]);
        }
    }
Copy after login

Running result:

1
2
2
3
4
5
7
8
9
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template