I\'m getting an arrayoutofboundsexception with this code....it prints out the ar
ID: 3552782 • Letter: I
Question
I'm getting an arrayoutofboundsexception with this code....it prints out the array of random generated integers but it wont print out the sorted elements from the algorithms, please fix where it works
System.out.println("Option 4 selected"); BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); randomGenerator = new Random(); System.out.print("Enter a positive integer n : "); size = Integer.parseInt(read.readLine()); System.out.print("Enter a positive integer M : "); int random = Integer.parseInt(read.readLine()); // create array a= new int[size]; int min=-17; int max=17; int range=max-min+1; // fill array for( i=0; i<size; i++) { a[i] = randomGenerator.nextInt()%range+min; } if(size<=100) { for(i=0; i<size; i++) { System.out.println("a[" + i + "] = " + a[i]); } } if(size>=100) { System.out.println(); } radixsort(a); System.out.println(" Elements after radix sort: "); for(i=0;i<size;i++) System.out.print(a[i]+" "); System.out.println(); quicksort(a); System.out.println(" Elements after quick sort"); for(i=0;i<size;i++) System.out.print(a[i]+" "); System.out.println(); break; Explanation / Answer
Below are the radix sort and quick sort methods in java
// RADIX SORT JAVA
static void radixsort(int a[],int d)
{
int bmat[][],c[],e=1;
int i, j, k, m, digit, row, col;
bmat=new int[a.length][10];
c= new int[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<a.length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
}
// QUICK SORT JAVA
public static void quickSort(int[] a, int p, int r)
{
if(p<r)
{
int q=partition(a,p,r);
quickSort(a,p,q);
quickSort(a,q+1,r);
}
}
private static int partition(int[] a, int p, int r) {
int x = a[p];
int i = p-1 ;
int j = r+1 ;
while (true) {
i++;
while ( i< r && a[i] < x)
i++;
j--;
while (j>p && a[j] > x)
j--;
if (i < j)
swap(a, i, j);
else
return j;
}
}
private static void swap(int[] a, int i, int j) {
// TODO Auto-generated method stub
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.