I am working on a Merge Sort algorithm but I am having issues getting this pseudo code working properly. I am getting an array out of bounds error on line 100 " s[k] = u[i];"
I am not sure why it is wrong. It is based off the pseduo code. If someone could point me in the right direction it would be much apreciated.
Here is the algorithm:
Here is the code:
import java.util.Arrays;
import java.util.Random;
public class MergeSortAnalysis {
private static int[] aux;
public static void main(String[] args) {
/**
* Merge Sort CALL
*/
System.out.println("_____________________\nMerge Sort\n");
//random dta
int data[] =new int[10];
Random rand = new Random();
for (int i=0; i<=9;i++)
{
data[i] = rand.nextInt(50) + 1;
}
System.out.println("Data Input: ");
System.out.println(Arrays.toString(data));
printArray(data);
System.out.println("Sorted: ");
MergeSort(10,data);
/**
* Merge Sort 2 CALL
*/
System.out.println("_____________________\nMerge Sort 2\n");
//random input
int input[] =new int[10];
Random rand1 = new Random();
System.out.println("Input Before Sort: ");
for (int i=0; i<=9;i++)
{
input[i] = rand1.nextInt(50) + 1;
}
printArray(input);
MergeSortAnalysis.sort(input);
System.out.println("After Sort: ");
printArray(input);
}
/**
* Print Array
*
*/
public static void printArray(int p[]) {
System.out.println("Output");
System.out.println(Arrays.toString(p));
}
/**
* Merge Sort Code - does not work
*
*
*/
public static void MergeSort(int n,int s[]) {
int h=n/2;
int m=n-h;
int[] u = new int[h];
int[] j = new int[m];
if(n>1)
{
for(int i=0; i<h; i++)
{
u[i] = s[i];
}
for(int i=0; i<m; i++)
{
j[i] = s[h+i];
}
MergeSort(h,u);
MergeSort(m,j);
merge(h,m,u,j,s);
}
}
public static void merge(int h, int m, int u[], int v[],int s[]) {
int i, j, k;
i=j=k=0;
while(i<h && j<m)
{
if(u[i]<v[j])
{
s[k] = u[i];
}
else
{
s[k]=v[j];
j++;
}
k++;
}
if(i>=h)
{
for(int a=j; a<m; a++)
{
s[k] = v[a];
k++;
}
}else
{
for( int a=i; a<h;a++)
{
s[k] = u[a];
k++;
}
}
printArray(s);
}

