I have created a code for quick sorting the only problem is that sometimes it gives out the sorted array and sometimes it doesn't. Any idea as to why it would do that? The first part of always works obviously.. the part where it shows the array TO BE sorted but the next part shows up occasionally after I run it a lot of time.

This is part of my code:

```
public static final int max = 10;

public static void main(String[] args) {
    int[] toSortArray = new int[max];

    for (int i = 0; i < max; i++) {
        toSortArray[i] = (int) (Math.random() * 100);
    }

    System.out.println("The array to be sorted is:");

    for (int i = 0; i < max; i++) {
        System.out.print(" | " + toSortArray[i]);
    }
    System.out.println(" | ");

    // Beginning of the algorithm
    quicksortHelper(toSortArray, 0, max - 1);
    // End of the algorithm

    System.out.println("The sorted array is: ");
    for (int i = 0; i < max; i++) {
        System.out.print(" | " + toSortArray[i]);
    }
    System.out.println(" | ");
}

private static void quicksortHelper(int[] toSortArray, int first, int last) {
    if (first < last) {
        int splitpoint = partition(toSortArray, first, last);
        quicksortHelper(toSortArray, first, splitpoint - 1);
        quicksortHelper(toSortArray, splitpoint + 1, last);
    }
}

private static int partition(int[] toSortArray, int first, int last) {
    int pivot = toSortArray[first];
    int leftmark = first + 1;
    int rightmark = last;
    boolean done = true;

    while (done) {
        while (leftmark <= rightmark && toSortArray[leftmark] < pivot) {
            leftmark++;
        }

        while (leftmark <= rightmark && toSortArray[rightmark] > pivot) {
            rightmark--;
        }

        if (leftmark > rightmark) {
            done = false;
        } else {
            int temp = toSortArray[leftmark];
            toSortArray[leftmark] = toSortArray[rightmark];
            toSortArray[rightmark] = temp;
        }
    }

    int temp = toSortArray[rightmark];
    toSortArray[rightmark] = toSortArray[first];
    toSortArray[first] = temp;
    return rightmark;
}

```