Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

How to merge two arrays in Java into one sorted ArrayList?

I have lArr (left) {1,2,4,5} and rArr (right) {6,8,10,13}, I want to merge them into one sorted array, but my code is not functioning how I want it to.

private static ArrayList merge(int[] lArr, int[] rArr) {
    ArrayList mergedArray = new ArrayList();
    int i = 0;
    int j = 0;
    while (i < lArr.length && j < rArr.length) {
        if (lArr[i] < rArr[j]) {
            mergedArray.add(lArr[i]);
            i++;
        }
        // so up until here, the code runs,
        // but it never reaches the else segment.
        else {
            mergedArray.add(rArr[j]);
            j++;
        }
    }
    return mergedArray;
}

after calling the merge() method from the main, lArr(left array) is only displayed.

question from:https://stackoverflow.com/questions/65921525/how-to-merge-two-arrays-in-java-into-one-sorted-arraylist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should merge the arrays first and then sort the array.
You can easily merge the arrays by creating an ArrayList and for each element in your arrays, add them to the ArrayList, like this :

// just an example of values
int[] lArr = {1,2,8};
// just an example
int[] rArr = {-7,54,9,34,27};
ArrayList<Integer> mergedList = new ArrayList<Integer>();
// Loop through lArr and add each element to mergedList
for(int element : lArr) mergedList.add(element);
// Loop through rArr and add each element to mergedList
for(int element : rArr) mergedList.add(element);

Now you can sort the list using Collections.sort(list, comparator), like this :

Collections.sort(mergedList, new Comparator<Integer>() {
   // A comparator compares two value (logic)
   // This function needs to return 1 if a > b and -1 if b < a
   // and if a = b then 1 or -1 won't change anything
   public int compare(Integer a, Integer b){
      if(a > b) return 1;
      return -1;
   }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...