I have this java code for QuickSort that works if there are no duplicates, however if there are any duplicates, the QuickSort fails. For example, if I want to QuickSort {5,3,3,1,7} my code will output {1,3,3,7,5}, and I can't seem to figure out why this is the case. 

```
 public static void quickSort(Integer[] nums) {
    quickSort(nums, 0, nums.length-1);
}

private static void quickSort(Integer[] ary, int lo, int hi) {
    //pick num @ lo to be pivot
    int pivot = lo;
    int i = lo+1;
    int j = hi;

    if( lo==hi) {
        return;
    }

    while(i <j) {

        if(ary[i].compareTo(ary[pivot]) <=0  ) {
            i++;

        }
        else if(ary[j].compareTo(ary[pivot]) >=0 ) {
            j--;
        }
        else {
            int temp = ary[i];  
            ary[i] = ary[j];
            ary[j] = temp;

        }

    }
    if(i == hi && j == hi) {
        if(ary[pivot].compareTo(hi) > 0) {
            int temp = ary[pivot];
            ary[pivot] = ary[hi];
            ary[hi] = temp;
            pivot = hi;

        }
        else {
            int temp1 = ary[pivot];
            ary[pivot] = ary[i-1];
            ary[i-1] = temp1;
            pivot = i-1;

        }

    }
    if(lo < pivot -1) {
        quickSort(ary, lo, pivot-1);
    }

    if(pivot +1 < hi) {
        quickSort(ary, pivot+1, hi);
    }

}

```

If anyone could tell me what I'm doing wrong, that would be greatly appreciated!