java - Merging two sorted Arraylists into one sorted Arraylist -


my code should merge 2 sorted arraylists 1 sorted arraylist , if 1 of arraylists used not sorted should return null.

public class mergesorted { public static void merge(arraylist<integer> a, arraylist<integer> b) {      (int = 0, j = 0; j < b.size(); i++) {         if (i == a.size() || a.get(i) > a.get(j)) {             a.add(i, b.get(j++));         }     } }   } 

this attempted can't idea of returning null if not equal, im new java , second week please patient me. know should have if statement checking if sorted , else should include inside if?

the generic way this:

public class mergesort {      public static <t extends comparable<? super t>> list<t> merge(list<t> a, list<t> b) {         if (!issorted(a) || !issorted(b)) {             return null;         }          final list<t> result = new arraylist<t>(a.size() + b.size());         result.addall(a);         result.addall(b);          collections.sort(result);          return result;     }      private static <t extends comparable<? super t>> boolean issorted(final list<t> list) {         t previtem = null;         (t item : list) {              if (previtem != null && item.compareto(previtem) < 0) {                 return false;             }              previtem = item;         }          return true;     }  } 

you can replace these generic ts integer if need them...


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -