I have create a program to split an array into two arrays, then sort them after that merge them back together.
My program works perfectly when I invoke run()
directly, but when I use start()
I get a NullPointerException
.
Can anyone tell me how to fix this?
public class SortingClass extends Thread{
public int[] arr, arr0;
public SortingClass(int[] a){
this.arr = a;
}
@Override
public void run() {
this.arr0 = sorting(arr);
}
public int[] sorting(int[] a){
int value;
int j;
for (int i = 1; i < a.length; i++){
value = a[i];
j = i-1;
while( j>=0 && a[j]>value ){
a[j+1] = a[j];
j = j-1;
}
a[j+1] = value;
}
return a;
}
public static int[] merge(int[] A, int[] B) {
int size = A.length + B.length;
int C [] = new int [size];
int i, a = 0, b = 0;
for(i=0; i<size; i++){
if(a == A.length){
C[i] = B[b];
++b;
} else if(b == B.length){
C[i] = A[a];
++a;
} else if(A[a] > B[b]) {
C[i]=B[b];
++b;
} else {
C[i] = A[a];
++a;
}
}
return C;
}
public static void print(int[] a, int[] b){
System.out.println("Before \t After");
for (int i = 0; i < a.length; i++) {
System.out.printf("%d \t %d\n",a[i],b[i]);
}
}
public static void main(String[] args) {
int[] arr = new int[10];
int[] arr0;
Random r = new Random();
for(int i = 0; i<arr.length; i++){
//arr[i] = r.nextInt(100);
arr[i] = i;
}
int[] arr1,arr2;
arr1 = new int[arr.length/2];
arr2 = new int[arr.length/2];
int i = 0;
int j = 0;
while(i<arr.length){
if (i < arr.length/2){
arr1[i] = arr[i];
} else {
arr2[j] = arr[i];
j++;
}
i++;
}
SortingClass s1 = new SortingClass(arr1);
SortingClass s2 = new SortingClass(arr2);
s1.start();
s2.start();
arr0 = merge(s1.arr0,s2.arr0);
print(arr, arr0);
}
}