Combina a clasificación con Arraylist en Java: Java, Array, Arraylist, MergeSort, Array-Merge

Estou tentando fusionar estas listas de arranxo. A lista3 é a última. Todo funciona ben, pero o último número, 400, non aparecerá na matriz final. Non teño idea de por que ou que facer. Estou tentando ordenar a Arraylist e estou case listo, excepto o último número que non aparece.

import java.util.ArrayList;public class TextLab12st{public static void main(String args){int jsaList1 = {101, 105, 115, 125, 145, 165, 175, 185, 195, 225, 235, 275, 305, 315, 325, 335, 345, 355, 375, 385};int jsaList2 = {110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 270, 280, 320, 350, 400};Array list1 = new Array(jsaList1,"List #1");Array list2 = new Array(jsaList2,"List #2");Array list3 = new Array("Merged List");list3.merge(list1,list2,list3);list1.display();list2.display();list3.display();}}class Array{private ArrayList<Integer> list;private int size;private String listName;public Array(String ln){list = new ArrayList<Integer>();size = 0;listName = ln;}public Array(int jsArray, String ln){list = new ArrayList<Integer>();size = jsArray.length;listName = ln;for (int j = 0; j < size; j++)list.add( new Integer( jsArray ));}public void display (){System.out.println("n" + listName + ":n");System.out.println(list + "n");}public void merge(Array that, Array theOther, Array result){{// Merge both halves into the result array// Next element to consider in the first arrayint iFirst = 0;// Next element to consider in the second arrayint iSecond = 0;// Next open position in the resultint j = 0;// As long as neither iFirst nor iSecond is past the end, move the// smaller element into the result.while (iFirst < that.size && iSecond < theOther.size){if (that.list.get(iFirst) < theOther.list.get(iSecond)){result.list.add(that.list.get(iFirst));iFirst++;}else{result.list.add(theOther.list.get(iSecond));iSecond++;}j++;}}}

}

Respostas

4 para a resposta № 1

Despois do ciclo que se executa en ambas as matrices:

Debe ver se hai algo que permanece nunha das matrices despois de chegar ao final do outro:

if (iFirst < that,size) {//copy everything remaining in that to output} else if (iSecond < theOther.size) {//copy everything from theOther to output}

1 para a resposta № 2

// this condition stops when you reach the end of either list// you need to continue until you reach the end of both listswhile (iFirst < that.size && iSecond < theOther.size)

Deixa unha resposta

O teu enderezo electrónico non se publicará Os campos obrigatorios están marcados con *