Any good java developer who can find the mistake ?

+1 pratt 15 · February 5, 2015
I m trying a make a merge sort program in java and now I stuck with this error,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at Merge.merge(Main.java:36)
at Merge.rec_divide(Main.java:24)
at Merge.rec_divide(Main.java:22)
at Main.main(Main.java:61)




class Merge {
private int[] array;
private int nelem;

public Merge(int s) {
int max = s;
array = new int[max];
nelem = 0;
}

public void sort(int[] a) {
rec_divide(a, 0, a.length - 1);
}

public void rec_divide(int[] a, int lower, int upper) {
if (lower == upper)
return;
else {
int mid = (lower + upper) / 2;
rec_divide(a, lower, mid);
rec_divide(a, mid + 1, upper);
merge(a, lower, mid+1, upper);
}

}

public void merge(int[] a, int lower, int mid, int upper) {
int lowptr = lower;
int midptr = mid -1;
int upptr = upper;

while (lowptr <= mid && midptr <= upper) {
if (a[lowptr] < a[midptr])
array[nelem++] = a[lowptr++];
else
array[nelem++] = a[midptr++];
}
while (lowptr <= mid)
array[nelem++] = a[lowptr++];
while (midptr <= upper)
array[nelem++] = a[midptr++];

}

public void display(){
for(int i=0;i<array.length;i++)
System.out.print(array+" ");
System.out.println();

}
}

public class Main {
public static void main(String args[]) {

int[] b={6,2,7,1,9,3};
Merge obj=new Merge(6);
obj.rec_divide(b,0,5);
obj.display();
}
}


Plz rectify my error coz i had tried to fix it 100 times. :'(

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · February 15, 2015

package Sorts;


class MergeSort
{
int[] m_array;

public MergeSort()
{
this.m_array=null;
}

public void sort(int[] a, int start)
{
if(a==null)
return;
this.m_array=mergeSortImpl(a,start);
}

public void sort(int[] a)
{
if(a==null)
return;
int position=1;
while(position
Here is a completed version of merge sort. If this isn't what you were looking for, be more specific and just adapt the implementation towards what you want it to do. I hope I showed what is occurring at each stage clearly. 
0 Dol Lod · February 16, 2015
Sorry, looks like something went wrong somehow. 


package Sorts;


class Sorter
{
int[] m_array;

public Sorter()
{
this.m_array=null;
}

public void mergeSort(int[] a, int start)
{
if(a==null)
return;
this.m_array=mergeSortImpl(a,start);
}

public void mergeSort(int[] a)
{
if(a==null)
return;
int position=1;
while(position
  • 1

Java / Android Development

107,190 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator