arraylist - Merge sort with array lists in java -
so homework have write program mergesorts array lists code works regular arrays, wondering if me figure out went wrong, because code throws ton of null pointer exceptions, , have tried fix them, when fix 1 goes another...and on....
thanks! code:
private static arraylist<integer> numbers= new arraylist<integer>(); private static arraylist<integer> helper; private static int number; public static void sort(arraylist<integer> mynumbers){ for(int i=0; i<mynumbers.size();i++){ numbers.add(mynumbers.get(i)); } //numbers=mynumbers; number = mynumbers.size()-1; mergesort(0, number -1); } private static void mergesort(int low, int high){ //check if low smaller high, if not array sorted if(low<high){ //get index of element in middle int middle=low+(high-low)/2; //sort left side of array mergesort(low, middle); //sort right side of array mergesort(middle +1, high); //combine them both merge(low, middle, high); } } private static void merge(int low, int middle, int high){ //copy both parts helper array for(int i=high;i>low;i++){ helper.add((numbers.get(i))); } int i=low; int j=middle+1; int k=low; //copy smallest mynumbers either left or right side original array while(i<middle && j<high){ if(helper.get(i)< helper.get(j)){ numbers.set(k,(helper.get(i))); i++; } else{ numbers.set(k,(helper.get(j))); j++; } k++; } //copy rest of left side of array target array while(i<middle){ numbers.set(k,helper.get(i)); k++; i++; } }
returns:
exception in thread "main" java.lang.nullpointerexception @ binarysearch.merge(binarysearch.java:61) @ binarysearch.mergesort(binarysearch.java:55) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.mergesort(binarysearch.java:51) @ binarysearch.sort(binarysearch.java:43) @ binarysearch.main(binarysearch.java:25)
here's culprit:
for(int i=high;i>low;i++){ helper.add((numbers.get(i))); }
use for(int i=high; i>=low; i--) {
instead.