I've been working on this all day and have no idea why this isn't working. The sort is duplicating some elements and is sorting some of the array but I can't see what is causing this. Tried to trace it but couldn't follow it.
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        int[] array = new int[10];
        for(int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random()*5);
        }
        int[] temp = array.clone();
        int l = 0;
        int r = array.length-1;
        System.out.println("unsorted "+Arrays.toString(array));
        mergeSort(array, temp, l, r);
        System.out.println("sorted "+Arrays.toString(array));
    }
    public static void mergeSort(int[] array, int[] temp, int p, int r) {
        int q = (p + r)/2;
        if(p < r) {
            mergeSort(array, temp, p, q);
            mergeSort(array, temp, q+1, r);
            merge(array, temp, p, q, r);
        }
    }
    public static void merge(int[] array, int[] temp, int p, int q, int r) {
        int i = p;
        int j = q + 1;
        for(int k = p; k < r; k++){
        if(i > q){
            array[k] = temp[j];
            j++;
        } else if(j > r) {
            array[k] = temp[i];
            i++;
        }  
        else if(temp[j] < temp[i]) {
            array[k] = temp[j];
            j++;
        } else {
            array[k] = temp[i];
            i++;
        }
      }
    }
}
 
    