eclipse - Simple MergeSort Java -
i have class lab due tomorrow , absolutely stumped. requirement simply: make mergesort algorithm sorts given arraylist using comparables. "a" have final sorted list. throwing following:
exception in thread "main" java.lang.indexoutofboundsexception: index: 1, size: 1 @ java.util.arraylist.rangecheck(arraylist.java:653) @ java.util.arraylist.get(arraylist.java:429) @ sorts.merge(sorts.java:142) @ sorts.mergesort(sorts.java:161) @ sorts.mergesort(sorts.java:160) @ sorts.mergesort(sorts.java:159) @ sortstep.sortmenu(sortstep.java:65) @ sortstep.main(sortstep.java:168)
anything helps! thanks! (i know line numbers don't guys. sorry!)
/** * takes in entire vector, merge following sections together: * left sublist a[first]..a[mid], right sublist a[mid+1]..a[last]. * precondition: each sublist in ascending order * * @param * reference array of integers sorted * @param first * starting index of range of values sorted * @param mid * midpoint index of range of values sorted * @param last * last index of range of values sorted */ private void merge(arraylist<comparable> a, int first, int mid, int last) { arraylist<comparable> temp = new arraylist<comparable>(); while (first <= mid && mid <= last) { if (a.get(first).compareto(a.get(mid)) > 0) { temp.add(a.get(first)); first++; } else { temp.add(a.get(mid)); mid++; } } while (first < mid) { temp.add(a.get(first)); first++; } while (mid <= last) { temp.add(a.get(mid)); mid++; } (int = 0; <= last; i++) a.set(i, temp.get(i)); } /** * recursive mergesort of array of integers * * @param * reference array of integers sorted * @param first * starting index of range of values sorted * @param last * ending index of range of values sorted */ public void mergesort(arraylist<comparable> a, int first, int last) { if (first < last) { int mid = (first + last) / 2; mergesort(a, first, mid); mergesort(a, mid + 1, last); merge(a, first, last, mid); } }
- the method
merge
expect argumentsfirst, mid, last
, passedfirst, last, mid
. mid
moving ahead, elements may stored intemp
.- the last loop of
merge
wrong , should start infirst
when method called, not0
. - the range of each section wrong.
corrected code:
private void merge(arraylist<comparable> a, int first, int mid, int last) { arraylist<comparable> temp = new arraylist<comparable>(); mid++; int firstfirst = first; int firstend = mid; while (first < firstend && mid <= last) { if (a.get(first).compareto(a.get(mid)) > 0) { temp.add(a.get(first)); first++; } else { temp.add(a.get(mid)); mid++; } } while (first < firstend) { temp.add(a.get(first)); first++; } while (mid <= last) { temp.add(a.get(mid)); mid++; } (int = firstfirst; <= last; i++) a.set(i, temp.get(i - firstfirst)); } public void mergesort(arraylist<comparable> a, int first, int last) { if (first < last) { int mid = (first + last) / 2; mergesort(a, first, mid); mergesort(a, mid + 1, last); merge(a, first, mid, last); } }
Comments
Post a Comment